Reputation: 81
I am trying to update user position in leaflet.Like when user walks with phone their location marker will move too based on location data just like google maps.
Right now im just putting a marker on their initial position
this.map.locate({
setView: true,
maxZoom: 120
}).on("locationfound", e => {
leaflet.marker([e.latitude, e.longitude]).bindPopup("YOU ARE HERE!").addTo(this.map);
console.log("lokasyon bulundu");
}).on("locationerror", error => {
console.log("lokasyon bulunamadi");
});
Tried update() method but couldnt make it work.i guess i should take user location data every second and if it different then draw new marker and remove old one ? is this a efficient way ?
thanks edit this is what i tried based on answer. its not working.im pulling data from db and based on that determining custom marker
this.map.locate({
setView: true,
maxZoom: 120,
watch:true,
enableHighAccuracy:true
}).on("locationfound", e => {
if (!usermarker) {
if(this.profileData.avatar == "https://i.hizliresim.com/zJJ239.png"){
usermarker = new L.marker(e.latlng,{icon : ayi}).addTo(this.map);
}else if(this.profileData.avatar == "https://i.hizliresim.com/mJJrkP.png"){
usermarker = new L.marker(e.latlng,{icon : ironman}).addTo(this.map);
}else if(this.profileData.avatar == "https://i.hizliresim.com/vJJQpp.png"){
usermarker = new L.marker(e.latlng,{icon : dino}).addTo(this.map);
}else if(this.profileData.avatar == "https://i.hizliresim.com/zJJ2B9.png"){
usermarker = new L.marker(e.latlng,{icon : petyr}).addTo(this.map);
}
} else if(this.profileData.avatar == "https://i.hizliresim.com/zJJ239.png") {
usermarker.setLatLng(e.latlng);
}
}).on("locationerror", error => {
if (usermarker) {
map.removeLayer(usermarker);
usermarker = undefined;
}
});
Upvotes: 0
Views: 5353
Reputation: 28628
Just check if there is a marker created, if not create it otherwise update it by using L.Marker's setLatLng
method:
Changes the marker position to the given point.
Reference: http://leafletjs.com/reference-1.2.0.html#marker-setlatlng
Example:
var marker;
this.map.locate({
setView: true,
maxZoom: 120
}).on("locationfound", e => {
if (!marker) {
marker = new L.marker(e.latlng).addTo(this.map);
} else {
marker.setLatLng(e.latlng);
}
}).on("locationerror", error => {
if (marker) {
map.removeLayer(marker);
marker = undefined;
}
});
Upvotes: 4