how to clear leaflet map of all markers and layers before adding new ones?

半世苍凉 提交于 2019-12-03 22:07:53

If you want to remove all the current layers (markers) in your group you can use the clearLayers method of L.markerClusterGroup(). Your reference is called markers so you would need to call:

markers.clearLayers();

You're losing the marker reference because it's set with var. Try saving the references to 'this' instead.

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);
    });
    [...]
}

Then later when you need to remove the markers run:

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

Alternatively, instead of saving each reference to each marker, you can just save the cluster to 'this'.

Prayitno Ashuri
map._panes.markerPane.remove();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!