4

I am trying to update user position in leaflet. Like when the user walks with their phone their location marker will move too based on location data just like Google Maps.

Right now I'm 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 couldn't make it work. I guess I should take user location data every second and if it is different then draw a new marker and remove the old one?

Is this an efficient way?

edit: tried this but not working

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;
          }
      });

1 Answer 1

5

For continous watch add option

watch: true

Here http://leafletjs.com/reference-1.2.0.html#locate-options is the list of all locate options.

This is the code I tested (Android 7.0) and that works for me:

function onLocationFound(e) {
  var radius = e.accuracy / 2;
  L.marker(e.latlng).addTo(map)
    .bindPopup("You are within " + radius + " meters from this point").openPopup();
  L.circle(e.latlng, radius).addTo(map);
}

map.on('locationfound', onLocationFound);
map.locate({setView: true, watch: true, maxZoom: 8});
2
  • Hi i tried something added on first post put its not working. Oct 29, 2017 at 13:38
  • Modified my answer with the code that works for me.
    – TomazicM
    Oct 30, 2017 at 16:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.