0👍
✅
This is my code for geolocation with position marker for Vue.js and leaflet.js. It’s Vue.js mixin.
For radius, you can simply increase or decrease lat and lng.
import * as L from 'leaflet';
// Geolocation marker icon
const locationMarker = L.icon({
iconUrl: require('@/assets/img/LocationMarker.svg'),
iconSize: [30, 30],
iconAnchor: [13, 30],
popupAnchor: [0, -18],
});
export default {
// Geo API for mobile
// Find current device position
beforeCreate() {
if (navigator.geolocation) {
return;
}
navigator.geolocation.getCurrentPosition((position) => {
this.isLoading = true;
this.position = position.coords;
if (this.center) {
this.center.lat = position.coords.latitude;
this.center.lng = position.coords.longitude;
}
});
},
methods: {
/**
* GeoLocation API
*/
geoLoc() {
// If geo exist
if (window.navigator.geolocation) {
// Give me position
window.navigator.geolocation.getCurrentPosition((position) => {
// Get coords from position
const lat = position.coords.latitude;
const lng = position.coords.longitude;
// Initialization Vue geoMarker
const geoMarker = this.geoMarker;
// Check if geomarker have the ID which I need
if (geoMarker.hasOwnProperty(this.geoMarkerId)) {
// If have than remove it
this.map.removeLayer(geoMarker[this.geoMarkerId]);
}
// Than create new one with the same static ID
let marker = L.marker(L.latLng(parseFloat(lat), parseFloat(lng)), {
icon: locationMarker,
});
// Must be in new array !!
this.geoMarker[this.geoMarkerId] = marker.addTo(this.map);
// Update Leaflet Map with new center coords
this.center = new L.LatLng(lat, lng);
// Then remove it
setTimeout(() => {
this.map.removeLayer(marker);
}, 7000);
});
} else {
// Och noo someone have any Geolocation :(
window.alert(this.$t('general.geoLocNotSupported'));
}
},
},
};
Source:stackexchange.com