传单当前位置多个标记

Leaflet current position multiple markers

大家好,我有一些关于传单中当前位置标记的问题,它应该每 3 秒更新一次,但它每次都会在地图上放置一个新的“位置”标记,而旧的保持不变怎么办我解决这个问题?

L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
attribution: '© Leaflet 2021',
tileSize: 512,
zoomOffset: -1,
id: 'mapbox/streets-v11',
accessToken: '######'
}).addTo(map);

    var greenIcon = L.icon({

    iconUrl: 'person.png',


    iconSize:     [35, 35], // size of the icon  // the same for the shadow
    popupAnchor:  [0, -20] // point from which the popup should open relative to the iconAnchor
    });
    // placeholders for the L.marker and L.circle representing user's current position and accuracy
    var current_position, current_accuracy;




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

                
        L.marker(e.latlng, {icon: greenIcon}).addTo(map)


    }




    // wrap map.locate in a function
    function locate() {
      map.locate({setView: true, maxZoom: 15});
    }



            map.on('locationfound', onLocationFound);

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

例如,您可以通过以下方式进行。 给标记添加一个ID(customId):

const marker = L.marker([lng, lat], {
  id: customId
});

当您添加新标记时,使用以下代码移除现有标记:

map.eachLayer(function(layer) {
  if (layer.options && layer.options.pane === "markerPane") {
    if (layer.options.id !== customId) {
      map.removeLayer(layer);
    }
  }
});

解决此问题的一种有效方法是保留对您创建的标记的引用,这样您就可以更新其位置,而不是每次获得位置更新时都创建一个新标记。引用需要保存在回调函数外部的变量中,但在创建回调时在范围内。

例如,您的回调可以检查标记是否已经存在,然后创建它并将其附加到 map 对象以便于重复使用,或者如果它已经存在则更新其坐标:

function onLocationFound(e) {
    var radius = e.accuracy / 2;
    
    if (map._here_marker) {
        // Update the marker if it already exists.
        map._here_marker.setLatLng(e.latlng);
    } else {
        // Create a new marker and add it to the map
        map._here_marker = L.marker(e.latlng, {icon: greenIcon}).addTo(map);
    }
}

有了这个参考,您还可以通过其他功能编辑标记,例如更改图标或弹出窗口,将其从视图中隐藏等。