Search code examples
javascriptgeolocationleaflet

Geolocation Leaflet Marker not removing old one


I have some Leaflet geolocation code which every time it updates the geolocation I get a new marker but the old markers are not removed so I'm ending with lots of markers instead of one.

Here is the code:

function locate() {
  mymap.locate({setView: true, maxZoom: 16});
}

function onLocationFound(e) {

    var radius = e.accuracy;

      L.marker(e.latlng).addTo(mymap)
        .bindPopup("You are within " + radius + " meters from this point " + Math.floor(Math.random() * 10) + " >>").openPopup();

    L.circle(e.latlng, radius).addTo(mymap);
}

mymap.on('locationfound', onLocationFound);

// call locate every 3 seconds... forever
setInterval(locate, 5000);

Solution

  • You have no code to remove the marker, so it doesn't get removed.

    Try this (adapted from https://gis.stackexchange.com/a/182084/120862):

    var currentlocation, currentradius;
    
    function locate() {
      mymap.locate({setView: true, maxZoom: 16});
    }
    
    function onLocationFound(e) {
    
        var radius = e.accuracy;
    
        if (currentlocation)  { 
             mymap.removeLayer(currentlocation);
             mymap.removeLayer(currentradius);
        }
    
    
          currentlocation = L.marker(e.latlng).addTo(mymap)
            .bindPopup("You are within " + radius + " meters from this point " + Math.floor(Math.random() * 10) + " >>").openPopup();
    
          currentradius = L.circle(e.latlng, radius).addTo(mymap);
    }
    
    mymap.on('locationfound', onLocationFound);
    
    // call locate every 3 seconds... forever
    setInterval(locate, 5000);