Danzo Sama
Danzo Sama

Reputation: 47

Remove markers from Leaflet.markercluster when they are clustered

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:

before deleted

After successful deletion:

after deleted

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

Upvotes: 2

Views: 1361

Answers (1)

ghybs
ghybs

Reputation: 53185

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.

Upvotes: 1

Related Questions