Skip to content

Instantly share code, notes, and snippets.

@shreyasmalewar
Created February 17, 2021 08:08
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save shreyasmalewar/e1fc20233debfc07f7236ad12561c71d to your computer and use it in GitHub Desktop.
Save shreyasmalewar/e1fc20233debfc07f7236ad12561c71d to your computer and use it in GitHub Desktop.
Using Google Maps API for Location Picker with Vue 2
<template>
<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>
</template>
<script>
export default {
name: "App",
data() {
return {
marker: { position: { lat: 10, lng: 10 } },
center: { lat: 10, lng: 10 },
mapOptions: {
disableDefaultUI: true,
},
};
},
mounted() {
this.geolocate();
},
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);
},
},
};
</script>
import Vue from "vue";
import App from "./App.vue";
Vue.config.productionTip = false;
import * as VueGoogleMaps from "vue2-google-maps";
Vue.use(VueGoogleMaps, {
load: {
key: "API_key",
},
installComponents: true,
});
new Vue({
render: (h) => h(App),
}).$mount("#app");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment