Leaflet using a variable for addTo(map)

5765
4
Jump to solution
11-28-2016 07:27 AM
Labels (1)
BillChappell
Occasional Contributor II

OK, I have a simple cancer web map in Leaflet and I'm stumped on a problem.

1. I have an HTML check box which when clicked turns on a layer. (Layer switcher is not an option) this basically calls a function and passes the cancer layer name. i.e.updateLayerVis("lung")

 

2. I have different types of cancer defined by name. i.e. var throat = new L.GeoJSON(data .....

 

3. So the function listed above passes the value 'lung' to 'a' below. It appears to be passing a dumb string called 'lung' while addTo is looking for a layer. Is it possible to use this string to add the appropriate layer to the map?

 

 

function updateLayerVis(a){

console.log(a); // lung

a.value.addTo(map); // returns an error "a.addTo is not a function"

a.addTo(map); // returns an error "a.addTo is not a function"

lung.addTo(map); //works but with 15 check boxes, I'd need a large switch function.

};

0 Kudos
1 Solution

Accepted Solutions
FC_Basson
MVP Regular Contributor

Instead of creating a variable with the name of each data layer, rather create a list of layers with the layer name as an index e.g.

var maplayers = [];
maplayers["lung"] = new L.GeoJSON(data...
maplayers["throat"] = new L.GeoJSON(data...

Then when clicking on the checkbox you can use the string value to activate the indexed layer.

function updateLayerVis(a){
   var lyr = maplayers[a];
   lyr.addTo(map);
}‍‍‍

View solution in original post

4 Replies
JohnGravois
Frequent Contributor
0 Kudos
FC_Basson
MVP Regular Contributor

Instead of creating a variable with the name of each data layer, rather create a list of layers with the layer name as an index e.g.

var maplayers = [];
maplayers["lung"] = new L.GeoJSON(data...
maplayers["throat"] = new L.GeoJSON(data...

Then when clicking on the checkbox you can use the string value to activate the indexed layer.

function updateLayerVis(a){
   var lyr = maplayers[a];
   lyr.addTo(map);
}‍‍‍
BillChappell
Occasional Contributor II

I was going toward this route when I saw your answer. It was cleaner then mine so I tried it. I also tried mapLayers.addTo(map); and this worked.

FC_Basson
MVP Regular Contributor

Yes, applying the addTo function directly to the indexed layer item should also work.  It's just nice to have the item available as a short variable if you need to refer to it further down in the function again.

0 Kudos