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

Pat*_*cow 30 javascript maps google-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();
        }
Run Code Online (Sandbox Code Playgroud)

我最初调用此函数,它将添加所有events标记和群集的地图.

在某些其他事件中传递的泡沫点,地图将放大到新事件,但旧的事件仍然在地图上.

我尝试了this.map.removeLayer(markers);一些其他的东西,但我不能让旧的标记消失

有任何想法吗?

iH8*_*iH8 41

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

markers.clearLayers();
Run Code Online (Sandbox Code Playgroud)

  • L.markerClusterGroup()默认不是Leaflet的一部分;可以用 L.layerGroup() 替换 (3认同)
  • 你刚刚救了我的命。 (2认同)

小智 16

你丢失了标记参考,因为它是用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);
    });
    [...]
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

  • 谢谢,`markers.clearLayers();` 成功了,但你使用 `this` 有好处,否则我做不到 (2认同)

小智 7

map._panes.markerPane.remove();
Run Code Online (Sandbox Code Playgroud)

  • 它只是删除图像! (3认同)