3

I can't remove a Leaflet layer from my map. I have referenced a lot of other SO threads about this very subject. Even so, removeLayer() refuses to work. addLayer() works just fine.

Threads I've visited (among others):

leaflet-layers-on-different-zoom-levels-how

leaflet-how-do-you-use-removelayer

function-with-map-addlayer-and-map-removelayer-not-working

map.on('zoomend', function() {

    const npsBoundaries = L.esri.featureLayer({
        url: 'https://services1.arcgis.com/fBc8EJBxQRMcHlei/ArcGIS/rest/services/National_Park_Service_Boundaries/FeatureServer/0',
        style: function(feature) {
            return { color: 'gray' };
        }
    });

    if (map.getZoom() > 6.5) {
        map.addLayer(npsBoundaries);      // <-- this works
    } else if (map.getZoom() <= 6.5) {
        map.removeLayer(npsBoundaries).   // <-- why doesn't this work?
    }

If it helps, I am using Leaflet v1.7

5

You should add a condition to if statement whether the layer exists. If you don't do this, you will add one more layer for each 'zoomend'.

Use this way:

const npsBoundaries = L.esri.featureLayer({
    url: 'https://services1.arcgis.com/fBc8EJBxQRMcHlei/ArcGIS/rest/services/National_Park_Service_Boundaries/FeatureServer/0',
    style: function (feature) {
        return { color: 'gray' };
    }
});

map.on('zoomend',
    function () {
        if (map.getZoom() > 6.5 && !map.hasLayer(npsBoundaries)) {
            map.addLayer(npsBoundaries);
        }
        if (map.getZoom() <= 6.5 && map.hasLayer(npsBoundaries)) {
            map.removeLayer(npsBoundaries)
        }
    }
);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.