0

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

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

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.