How to remove markers if they clustered? Because if they are grouped, you cannot delete. But as soon as the grouping disappears, then everything is fine.
Before trying to delete:
After successful deletion:
Code for add markers:
var markers = L.markerClusterGroup();
map.addLayer(markers);
L.geoJSON(data, {
pointToLayer: pointToLayer,
onEachFeature: onEachFeature,
})
.on('click', markerOnClick)
.addTo(markers);
Code for delete 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);
}
}
});
Simply use the eachLayer
method on your markers
Marker Cluster Group to iterate over each child Marker (whether they are currently clustered or not).
markers.eachLayer(layer => {
if(layer.feature.properties.obj == 2 && layer.feature.properties.type == 1) {
markers.removeLayer(layer);
}
});
When accessing markers._map._layers
, you look for each Layer currently on the map, but Leaflet.markercluster removes your Markers when they are clustered (and replaces them by the Cluster Marker instead). That is why you no longer find some Markers.