如何在添加新标记和图层之前清除所有标记和图层的传单地图

How to clear Leaflet map of all markers and layers before adding new ones?

本文关键字:图层 单地图 地图 添加 新标记 清除      更新时间:2024-02-11

我有以下代码:

map: function (events) {
    var arrayOfLatLngs = [];
    var _this = this;
    // setup a marker group
    var markers = L.markerClusterGroup();
    events.forEach(function (event) {
        // setup the bounds
        arrayOfLatLngs.push(event.location);
        // create the marker
        var marker = L.marker([event.location.lat, event.location.lng]);
        marker.bindPopup(View(event));
        // add marker
        markers.addLayer(marker);
    });
    // add the group to the map
    // for more see https://github.com/Leaflet/Leaflet.markercluster
    this.map.addLayer(markers);
    var bounds = new L.LatLngBounds(arrayOfLatLngs);
    this.map.fitBounds(bounds);
    this.map.invalidateSize();
}

我最初调用这个函数,它会将所有events添加到带有标记和簇的映射中。

稍后,我通过一些其他事件,地图会放大到新事件,但旧事件仍在地图上。

我尝试过this.map.removeLayer(markers);和其他一些东西,但我无法让旧的标记消失

如果要删除组中的所有当前层(标记),可以使用L.markerClusterGroup()clearLayers方法。您的参考号为markers,因此您需要致电:

markers.clearLayers();

您正在丢失标记引用,因为它是用var设置的。请尝试保存对"this"的引用。

mapMarkers: [],
map: function (events) {
    [...]
    events.forEach(function (event) {
        [...]
        // create the marker
        var marker = L.marker([event.location.lat, event.location.lng]);
        [...]
        // Add marker to this.mapMarker for future reference
        this.mapMarkers.push(marker);
    });
    [...]
}

然后稍后当您需要删除标记时运行:

for(var i = 0; i < this.mapMarkers.length; i++){
    this.map.removeLayer(this.mapMarkers[i]);
}

或者,您可以将集群保存到"this",而不是保存对每个标记的每个引用。

map._panes.markerPane.remove();
$(".leaflet-marker-icon").remove();
$(".leaflet-popup").remove();

您可以清除所有标记并保存

map.eachLayer((layer) => {
  layer.remove();
});

来自https://leafletjs.com/reference-1.0.3.html#map-事件

我在这里使用了beije和Prayitno Ashuri的两个最佳答案的组合。

将标记保存到"this",以便我们以后可以引用它。

this.marker = L.marker([event.location.lat, event.location.lng]);

然后移除标记。

this.markers.remove()