聚类时从 Leaflet.markercluster 中删除标记

Remove markers from Leaflet.markercluster when they are clustered

如果标记聚集在一起,如何去除它们?因为如果它们被分组,你就不能删除。但是一旦分组消失,就万事大吉了。

尝试删除之前:

删除成功后:

添加标记的代码:

var markers = L.markerClusterGroup();
map.addLayer(markers);

L.geoJSON(data, {
                pointToLayer: pointToLayer, 
                onEachFeature: onEachFeature,
            })
            .on('click', markerOnClick)
            .addTo(markers);

删除标记代码:

$.each(markers._map._layers, function (ml) {
    if (markers._map._layers[ml].feature) {
        if(markers._map._layers[ml].feature.properties.obj == 2 && markers._map._layers[ml].feature.properties.type == 1){                      
             markers.removeLayer(this);
        }            
    }
});

只需在您的 markers 标记集群组上使用 eachLayer method 来迭代每个子标记(无论它们当前是否集群)。

markers.eachLayer(layer => {
  if(layer.feature.properties.obj == 2 && layer.feature.properties.type == 1) {                      
    markers.removeLayer(layer);
  }
});

访问 markers._map._layers 时,您会查找当前地图上的每个图层,但 Leaflet.markercluster 会在您的标记聚类时将其移除(并用聚类标记代替)。这就是为什么您不再找到一些标记的原因。