地理定位传单标记不删除旧的

Geolocation Leaflet Marker not removing old one

我有一些 Leaflet 地理定位代码,每次它更新地理位置时我都会得到一个新标记,但旧标记没有被删除,所以我以很多标记而不是一个结束。

代码如下:

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

您没有删除标记的代码,因此它不会被删除。

试试这个(改编自 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);