1

I have a function which removes all my layers from the map individually:

function resetMap() {

map.removeLayer(Frog1Layer);
map.removeLayer(Frog2Layer);
map.removeLayer(Frog3Layer);
map.removeLayer(Frog4Layer);
map.removeLayer(Frog5Layer);
map.removeLayer(Frog6Layer);
map.removeLayer(Frog7Layer);
map.removeLayer(Frog8Layer);
}

I assume there's a better way? I tried making them into a group but the issue is, I have already added them to the map separately so they can be triggered by buttons on my page, and I don't know how to group them without adding them to the map as a group.

I tried the following:

function resetMap() {

    var allLayers = L.layerGroup([Frog1Layer, Frog2Layer, Frog3Layer, 
    Frog4Layer, Frog5Layer, Frog6Layer, Frog7Layer, Frog8Layer])

    map.removeLayer(allLayers);
}

and it doesn't work. The Web Console says "t is not defined" but I don't know what this means? What is t and why does L.layerGroup not work? How do I do this? Sorry, I'm new to Javascript.

Rashed Hasan
  • 3,721
  • 11
  • 40
  • 82
sophhGIS
  • 23
  • 1
  • 8
  • Maybe a duplicate of https://stackoverflow.com/questions/28646317/how-to-remove-all-layers-and-features-from-map ? (The answer appears to be `map.eachLayer(function (layer) { map.removeLayer(layer); });`) – apsillers Nov 05 '19 at 16:32
  • Sorry, I don't understand how to use this?? Can you elaborate – sophhGIS Nov 05 '19 at 16:55
  • The code in my comment can be used as the entire content of your `resetMap` function, and when run, it will remove all layers from `map`. – apsillers Nov 05 '19 at 17:04
  • It removed the map itself?? Is that supposed to happen? I want to keep the map tiles, but delete the 8 data layers. – sophhGIS Nov 05 '19 at 17:09
  • Ah, okay, that clarifies things. Your question is not how to remove *all* layers but how to remove a specific set of layers as concisely as possible. I'll answer shortly. – apsillers Nov 05 '19 at 17:12

1 Answers1

0

Assuming you have the layers you want to remove in an array, you can use forEach to iterate over the layers and remove each one from your map:

var layerArray = [Frog1Layer, Frog2Layer, Frog3Layer, Frog4Layer, Frog5Layer, Frog6Layer, Frog7Layer, Frog8Layer];
layerArray.forEach(function(layer) { map.removeLayer(layer); })

Removing a LayerGroup does not work unless that specific LayerGroup was added to the map. If you plan to use these layers together in other ways, it may be worth structuring them as a LayerGroup. If you want to do that, add them to the LayerGroup and then use map.addLayer to add the group object, instead of doing map.addLayer for each layer .

apsillers
  • 112,806
  • 17
  • 235
  • 239
  • Thank you! Using an array seems like the right idea, but I am still getting an alert in the WebConsole that says "t is undefined" Any idea what could be causing this? – sophhGIS Nov 05 '19 at 17:23