I am using React Leaflet and react-leaflet-markercluster. I have a lot of markers and if parent's state is changed, marker cluster rerendering takes longer time. For this reason, cluster components are memoized.
When I click on a polygon, I want to delete it's marker from map and markercluster. I am looking for a way to do it without rerendering markercluster. I tried this code, but it doesn't work:
React.useEffect(() => {
Object.keys(mapRef?._layers).forEach(function (key) {
const leafletLayer = mapRef?._layers[key];
if (typeof leafletLayer?.getAllChildMarkers === "function") {
const allMarkers = leafletLayer.getAllChildMarkers();
allMarkers.forEach((marker) => {
const dataId = marker.options.id;
const foundMarker = props.selected.find(
(selectedAsset) => selectedAsset === dataId
);
if (foundMarker) {
console.log("remove marker from map", marker);
mapRef.removeLayer(marker);
}
});
}
});
}, [mapRef, props.selected]);
L.MarkerCluster
and get an array of all the markers, I think we can do this, by removing the markers directly from the leaflet element and leaving react out of it. It seemsgetAllChildMarkers
is only available from within an event callback?react-leaflet-markercluster
wrapper and now I am using onlyLeaflet.markercluster
. I am storing markercluster reference in a variable which is out of react component. I am able to delete markers inReact.memo
function ofMapElements
component where I can access markercluster reference and delete markers.