4

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

Vince
  • 20,017
  • 15
  • 45
  • 64
Erich Purpur
  • 1,861
  • 3
  • 18
  • 35

1 Answers1

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

Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389