At times when creating apps like uber, which require the user to pick a location on the map we can use the Google Maps API. So let me show you how to build a location picker with Google Maps API using Vue 2.
If you do not know about Vue, I'd recommend you check it out here: Vue
Let us begin.
Prerequisites
- Creating a Vue app
Create a new Vue app using the following command:
$ npm install -g @vue/CLI
$ vue create gmaps-tutorial
$ cd gmaps-tutorial
$ npm run serve
This should get you an app server running which you can check out at localhost:8080.
- Obtaining Google Maps API Key
Go to: Google Cloud Console
Click on Library under API & Services
Click on "Maps Javascript API"
Click on "Create Credentials" and select the API key
Editing Code
Install Dependencies
$ npm i vue2-google-maps
In src/main.js
- Import VueGoogleMaps
import * as VueGoogleMaps from "vue2-google-maps";
- Initialize VueGoogleMaps
Vue.use(VueGoogleMaps, {
load: {
key: "API_KEY",
},
installComponents: true,
});
In src/App.vue
- Add the GmapMap & GmapMarker components GmapMap displays the map in the browser window and GmapMarker picks the location.
<div id="app">
<GmapMap
:center="center"
:zoom="18"
map-style-id="roadmap"
:options="mapOptions"
style="width: 100vmin; height: 50vmin"
ref="mapRef"
@click="handleMapClick"
>
<GmapMarker
:position="marker.position"
:clickable="true"
:draggable="true"
@drag="handleMarkerDrag"
@click="panToMarker"
/>
</GmapMap>
<button @click="geolocate">Detect Location</button>
<p>Selected Position: {{ marker.position }}</p>
</div>
- Declare the following as component data
data() {
return {
marker: { position: { lat: 10, lng: 10 } },
center: { lat: 10, lng: 10 },
mapOptions: {
disableDefaultUI: true,
},
};
}
- Add the following Methods to the component
methods: {
//detects location from browser
geolocate() {
navigator.geolocation.getCurrentPosition((position) => {
this.marker.position = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
this.panToMarker();
});
},
//sets the position of marker when dragged
handleMarkerDrag(e) {
this.marker.position = { lat: e.latLng.lat(), lng: e.latLng.lng() };
},
//Moves the map view port to marker
panToMarker() {
this.$refs.mapRef.panTo(this.marker.position);
this.$refs.mapRef.setZoom(18);
},
//Moves the marker to click position on the map
handleMapClick(e) {
this.marker.position = { lat: e.latLng.lat(), lng: e.latLng.lng() };
console.log(e);
},
},
};
- If you wish to automatically detect the location on the application load add
geolocate
to themounted
hook
mounted() {
this.geolocate();
},
This should give you a map that lets you select your location by clicking on it. Now you can extend this component to use as you like.
The complete example can be found here Github Gist
Top comments (3)
This tutorial seems to be missing the bit where you npm install the VueGoogleMaps package.
Thanks! Updated.
Interesting gonna try it