Leaflet- add and remove all layers in list based on variable

first let me state I am not very good at Javascript and I have a feeling this is a simple formatting matter.

I am trying to add and remove layers to a map based on a variable; in this case num. I have functions that add or remove to num based on clicks.

I can add and remove one layer easily with the if statements in the below code. what I would like to do is build a list of layers and then iterate through them and to add or remove them from the map.

this is what I have

 var one = [Township,Section] \\list of layers
 for (i = 0; i < one.length; i++) {
  if (num != 1 && map.hasLayer(i)) {
    map.removeLayer(i);
  }
  if (num == 1 && map.hasLayer(i) == false)
    {
      map.addLayer(i);
    }
  }  

The If statement works fine with one layer (without for statement) but I cannot get it to run through all layers in the list one.

if anyone has any thoughts I would appriciate it.

Upvotes: 0

Views: 243

Answers (1)

user3802409
user3802409

Reputation:

i is an integer value, not a layer. So map.hasLayer(i) and map.removeLayer(i) takes wrong type of parameter. Try to use map.hasLayer(one[i]) and map.removeLayer(one[i])

EDIT: Also map.addLayer(one[i])

Upvotes: 1

Related Questions