
ReactiveGoogleMap creates a data-driven map UI component using Google Maps. It is the key component for building map based experiences.
Example uses:
- showing a map of user check-ins by city and topics for powering discovery based experiences.
- displaying restaurants filtered by a nearby distance query on a map.
Usage
Installation
<reactive-google-map /> uses Google Maps JS library to render the google map and access the necessary geo-location services. To configure the google maps you have to install the ReactiveGoogleMap plugin with google maps key. For example,
import Vue from 'vue';
import App from './App.vue';
import {
ReactiveBase,
ReactiveGoogleMap,
} from '@appbaseio/reactivesearch-vue';
Vue.use(ReactiveBase);
// Installing the ReactiveGoogleMap plugin
Vue.use(ReactiveGoogleMap, {
key: 'PUT_YOUR_MAP_KEY',
});
Vue.config.productionTip = false;
new Vue({
render: h => h(App),
}).$mount('#app');
Nuxt.js config
If you're using Nuxt.js then you have to add the following to the build section of your nuxt.config.js file:
transpile: [/^gmap-vue($|\/)/, /^@appbaseio\/reactivesearch-vue($|\/)/],You can also check this example with Nuxt.js.
Basic Usage
<reactive-google-map
componentId="MapUI"
dataField="location"
/>Usage With All Props
<reactive-google-map
componentId="MapUI"
dataField="location"
:size="10"
:defaultZoom="13"
:defaultCenter="{ lat: 37.74, lng: -122.45 }"
:defaultRadius="200"
:unit="mi"
:showMarkerClusters="true"
:showSearchAsMove="true"
:searchAsMove="true"
:autoCenter="true"
:pagination="true"
:react="{
and: 'CitySensor',
}"
/>Props
-
componentId
Stringunique identifier of the component, can be referenced in other components'reactprop. -
dataField
StringDB data field to be connected to the component's UI view, usually of a geopoint (i.e. location) data type and used for rendering the markers on the map. -
size
Number[optional] number of results to show in the map view, can be a number in the range [1, 1000]. Defaults to 10. -
calculateMarkers
Function[optional] TheReactiveGoogleMapcomponent uses the ElasticSearchhitsto render the markers, if you wish to override the default markers thencalculateMarkersprop is the way. ThecalculateMarkersfunction accepts an object with following properties:data, parsed hits datarawData, Elasticsearch raw response
The function must return an array of markers where each marker must have the following properties:
_id, unique identifier for each marker- [dataField], location object with
latandlngvalues.
Note: The
dataFieldkey should be similar to thedataFieldprop defined for theReactiveGoogleMapcomponent. For example, if yourdataFieldname islocationthen the marker object would look like below:{ "_id": "xyz", "location": { lat: 37.7749, lng: 122.4194, } }You can check the following example that uses the Elasticsearch aggregations to render the markers. https://codesandbox.io/s/github/appbaseio/reactivesearch/tree/vue-maps/packages/vue/examples/reactive-google-map-aggregations?file=/src/App.vue
-
clusterProps
Object[optional] can be used to bind the properties to the Google Maps Cluster object. It supports the following properties:- maxZoom
Number - batchSizeIE
Number - calculator
Function - enableRetinaIcons
Boolean - gridSize
Boolean - averageCenter
Boolean - ignoreHidden
Boolean - imageExtension
Boolean - imagePath
String - imageSizes
Array - minimumClusterSize
Number - clusterClass
String - styles
Array - zoomOnClick
Boolean
- maxZoom
-
defaultZoom
Number[optional] preset map's zoom level, accepts integer values between [0, 20]. 0 is the minimum zoom level, where you can see the entire globe. 20 is the maximum zoom level. Defaults to 13. -
defaultCenter
Object[optional] preset map's center position by specifying an object with validlatandlngvalues. This prop, when set, will cause the component to run a geo-distance query with a distance of 10mi (Refer:defaultRadiusandunitprop to configure the distance). -
defaultQuery
Function[optional] applies a default query to the map component. This query will be run when no other components are being watched (via React prop), as well as in conjunction with the query generated from the React prop. The function should return a query. Read more about it here. The following example uses thedefaultQuerywithcalculateMarkersto display the markers using Elasticsearchaggregationsinstead ofhits. https://codesandbox.io/s/github/appbaseio/reactivesearch/tree/vue-maps/packages/vue/examples/reactive-google-map-aggregations?from-embed=&file=/src/App.vue The following example changes thedefaultQuerywhenever the zoom value changes. https://codesandbox.io/s/github/appbaseio/reactivesearch/tree/vue-maps/packages/vue/examples/reactive-google-map-default-query?from-embed=&file=/src/App.vue -
center
Object[optional] set map's center position by specifying an object with validlatandlngvalues. This prop, when set, will cause the component to run a geo-distance query with a distance of 10mi (Refer:defaultRadiusandunitprop to configure the distance). -
defaultRadius
Number[optional] used as distance value for the geo-distance query whendefaultCenterorcenteris set. It accepts all positive integers. -
unit
String[optional] unit for distance measurement, usesmi(for miles) by default. Distance units can be specified from the following:
-
showMarkers
Boolean[optional] whether to show the markers on the map, defaults totrue. Sometimes, it doesn't make sense to display markers (when building a heatmap or weather map or a directions navigation map) -
defaultPin
String[optional] URL of the default marker pin image to be shown. It comes with a default image. Should only be set if you wish to use a custom marker. -
showMarkerClusters
Boolean[optional] whether to aggregate and form a cluster of nearby markers. Defaults totrue.
Note
- It requires
showMarkersprop enabled.- You have to define the [m1-m5] cluster images at
public/imagesfolder. Please check this example.
-
showSearchAsMove
Boolean[optional] whether to show the Search As I Move checkbox in the UI. Defaults totrue. -
searchAsMove
Boolean[optional] whether to set the Search As I Move checkbox. Defaults tofalse. -
searchAsMoveLabel
String[optional] allows to customize the default text for search as move button -
autoClosePopover
Boolean[optional] automatically closes the existing open popovers when a new marker is clicked. Defaults tofalse. -
react
Object[optional] specify dependent components to reactively update ReactiveGoogleMap's options. Read more about it here.- key
Stringone ofand,or,notdefines the combining clause.- and clause implies that the results will be filtered by matches from all of the associated component states.
- or clause implies that the results will be filtered by matches from at least one of the associated component states.
- not clause implies that the results will be filtered by an inverse match of the associated component states.
- value
String or Array or ObjectStringis used for specifying a single component by itscomponentId.Arrayis used for specifying multiple components by theircomponentId.Objectis used for nesting other key clauses.
- key
-
autoCenter
Boolean[optional] whether to auto center the map based on the geometric center of all the location markers. Defaults tofalse. -
className
String[optional] CSS class to be injected on the component container. -
style
Object[optional] CSS style object to be applied to theReactiveGoogleMapcomponent. -
pagination
Boolean[optional] When set totrue, a pagination based list view with page numbers will appear. -
renderItem
Function|slot-scope[optional] useful to customize the markers. It can be defined as aFunctionor slot. The following example would render the marker with a label.<reactive-google-map :renderItem="result => ({ label: result.title, })" />The following example would render the marker with an icon.
<reactive-google-map :renderItem="result => ({ icon: 'https://i.imgur.com/NHR2tYL.png', })" />The following example uses the
slotto customize the marker.<reactive-google-map> <div slot="renderItem" slot-scope="{ magnitude }"> {{result.mag}} </div> </reactive-google-map> -
renderPopover
slot-scope[optional] It is useful to render the popover content when a marker is clicked. The slot data would be an object with the following properties:-
item represents the marker data
-
handleClose useful to close the popover programmatically
The following example displays the
titleanddescriptionin popover.<reactive-google-map> <div slot="renderPopover" slot-scope="{ item }"> <div>{{ item.title }}</div> <p>{{ item.description }}</p> </div> </reactive-google-map> -
-
renderClusterPopover
slot-scope[optional] It is useful to render the popover content when a cluster is clicked. The slot data would be an object with the following properties:- markers An array of markers for the selected cluster
- cluster Cluster reference object
- handleClose useful to close the popover programmatically
The following example displays the
markersinformation for a particular cluster.<reactive-google-map> <div slot="renderClusterPopover" slot-scope="{ markers, cluster }"> <pre>{{ JSON.stringify(markers, null, 2) }}</pre> </div> </reactive-google-map>
-
render
slot-scope[optional] Therenderslot can be used to render the results in a list based UI.
It accepts an object with these properties:loading:booleanindicates that the query is still in progresserror:objectAn object containing the error infodata:arrayAn array of results obtained from combiningpromotedresults along with thehits.promotedData:arrayAn array of promoted results obtained from the applied query. Read MoreNote:
dataandpromotedDataresults has a property called_click_idwhich can be used with triggerClickAnalytics to register the click analytics info.customDataobjectCustom data set in the query rule when appbase.io is used as backend. Read MorerawDataobjectAn object of raw response as-is from elasticsearch query.resultStats:objectAn object with the following properties which can be helpful to render custom stats:numberOfResults:numberTotal number of results foundnumberOfPages:numberTotal number of pages found based on current page sizecurrentPage:numberCurrent page number for which data is being renderedtime:numberTime taken to find total results (in ms)displayedResults:numberNumber of results displayed in current viewhidden:numberTotal number of hidden results foundpromoted:numberTotal number of promoted results found
loadMore:functionA callback function to be called to load the next page of results into the view.triggerClickAnalytics:functionA function which can be called to register a click analytics. Read MoresetPage:functionA function which will allow to dispatch a page change event when using custom pagination. It acceptspageNumberas its parameter.
<reactive-google-map> <div slot="render" slot-scope="{ loading, error, data }"> <div v-if="loading">Fetching Results.</div> <div v-if="Boolean(error)">Something went wrong! Error details {{JSON.stringify(error)}}</div> <ul v-bind:key="result._id" v-for="result in data"> <li> {{result.title}} <!-- Render UI --> </li> </ul> </div> </reactive-google-map> -
renderError
String|Function|slot-scope[optional] can be used to render an error message in case of any error.<template slot="renderError" slot-scope="error"> <div>Something went wrong!<br />Error details<br />{{ error }}</div> </template>
Demo
Styles
ReactiveGoogleMap component supports innerClass prop with the following keys:
checkboxContainercheckboxlabel
Events
-
queryChange is an event which accepts component's prevQuery and nextQuery as parameters. It is called everytime the component's query changes. This event is handy in cases where you want to generate a side-effect whenever the component's query would change.
-
pageClick accepts a function which is invoked with the updated page value when a pagination button is clicked. For example if 'Next' is clicked with the current page number as '1', you would receive the value '2' as the function parameter.
-
data
Function[optional] gets triggered after data changes, which returns an object with these properties:data,promotedData,rawData,customData&resultStats. -
error gets triggered in case of an error and provides the
errorobject, which can be used for debugging or giving feedback to the user if needed. -
zoom-changed called whenever map zoom gets changed
-
drag-end gets triggered when map drag ends
-
idle gets called when map is in idle position
-
open-marker-popover gets called when marker popover gets opened or marker is clicked, the current marker object is also emitted along.
-
close-marker-popover gets called when marker popover is closed, the current marker object is also emitted along.
-
open-cluster-popover gets called when cluster popover gets opened or cluster is clicked, an array of associated marker objects is also emitted along.
-
close-cluster-popover gets called when cluster popover is closed
-
search-as-move gets called whenever Search As I Move checkbox is clicked. It returns the
checkedstate of the Search As I Move checkbox.
Extending
ReactiveGoogleMap component can be extended to
- customize the look and feel with
classNameandstyleprops, - render the results in a customized view using
renderslot. - customize the markers using
renderItemslot. - customize popover content using
renderPopoverslot. - get the google map reference using
refs. ThegetMapRefmethod ofReactiveGoogleMapcomponent would return the map ref.