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

时间:2015-02-20 19:26:54

标签: javascript google-maps maps leaflet

我有以下代码:

    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);和其他一些东西,但我无法让旧标记消失

任何想法?

6 个答案:

答案 0 :(得分:33)

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

markers.clearLayers();

答案 1 :(得分:12)

你丢失了标记参考,因为它是用var设置的。 请尝试将引用保存为“此”。

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

或者,您可以将群集保存为“此”,而不是将每个引用保存到每个标记。

答案 2 :(得分:0)

map._panes.markerPane.remove();

答案 3 :(得分:0)

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

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

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

答案 4 :(得分:0)

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

答案 5 :(得分:-3)

我结合了beije和Prayitno Ashuri的两个最佳答案。

将标记保存为“ this”,以便稍后使用。

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

然后删除标记。

this.markers.remove()