[GIS] Update marker position in Leaflet

leaflet

I would like to use this function to update the marker every time the GPS is detected, it works but always adds a new marker and circle.

function onLocationFound(e) {
        var radius = e.accuracy / 2;

        L.marker((e.latlng), {icon: IsyUserIcon}).addTo(map).bindPopup("You are within " + radius + " meters from this point").openPopup(); 
        L.circle(e.latlng, radius).addTo(map);
    }

Best Answer

You are creating new marker pair at each call of the function, so old markers stay where they are. Instead you should create new marker pair only once and at later calls just change their attributes.

Your function could then look something like this:

var gpsMarker = null;
var gpsCircleMarker;

function onLocationFound(e) {
  var radius = e.accuracy / 2;
  var popupContent = "You are within " + radius + " meters from this point";

  if (gpsMarker == null) {
    gpsMarker = L.marker(e.latlng, {icon: IsyUserIcon}).addTo(map);
    gpsMarker.bindPopup(popupContent).openPopup();
    gpsCircleMarker = L.circle(e.latlng, radius).addTo(map);
    }
  else {
   gpsMarker.getPopup().setContent(popupContent);   
   gpsMarker.setLatLng(e.latlng);
   gpsCircleMarker.setLatLng(e.latlng);
   gpsCircleMarker.setRadius(radius);
  }
}
Related Question