Leaflet Plugins – Unable to Remove Marker Cluster Group Completely From the Map

leafletleaflet-plugins

I am having a weird issue with removing a MarkerClusterGroup layer from the map. When at a zoom level more than 5, I want to show markers on the map in a MarkerClusterGroup layer. When zoomed to less than level 5, I want to remove the markers.

Given the code below, most of the markers remove, but a small cluster of markers in the center of the map stubbornly remains (all the markers and clusters are in the same FeatureGroup).

const LAYERS = {};
const BOUNDS = null;

const makeFoo = async (bounds) => {
    // get points for `bounds` from the server
    const url = `server/?bounds`;
    const response = await fetch(url);

    if (response.ok) {
        LAYERS.foo = L.markerClusterGroup();
        const records = await response.json();
        records.forEach((r) => LAYERS.foo.addLayer(L.marker(new L.LatLng(r.lat, r.lng)));
        map.addLayer(LAYERS.foo);
    }
}

const map = L.map( 'map', {});
map.on('moveend', function(e) {    
    if (map.getZoom() > 5) {
        if (BOUNDS) {
            if (map.bounds.contains(BOUNDS)) {
                if (!map.hasLayer(LAYERS.foo)) makeFoo(map.getBounds());
            }
            else {
                BOUNDS = map.getBounds();
                makeFoo(BOUNDS);
            }
        }
        else {
            BOUNDS = map.getBounds();
            makeFoo(BOUNDS);
        }
    }
    else if (zoom <= 5) {
        if (map.hasLayer(LAYERS.foo)) map.removeLayer(LAYERS.foo);
    }
});

When I type the following in the browser console, no layer is found, but I can see the points.

>> map.hasLayer(LAYERS.foo)
← false

What is going on? How can I get rid of these ghost marker clusters?

Best Answer

Without actually testing I would say that what's missing is removing possible existing marker cluster layer when creating a new one.

So probably the code should be something like:

const makeFoo = async (bounds) => {
    // get points for `bounds` from the server
    const url = `server/?bounds`;
    const response = await fetch(url);

    if (response.ok) {
        if (LAYERS.foo && map.hasLayer(LAYERS.foo)) {
          map.removeLayer(LAYERS.foo);
        }
        LAYERS.foo = L.markerClusterGroup();
        const records = await response.json();
        records.forEach((r) => LAYERS.foo.addLayer(L.marker(new L.LatLng(r.lat, r.lng)));
        map.addLayer(LAYERS.foo);
    }
}