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.
};
Solved! Go to Solution.
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);
}
check out this stack overflow thread.
http://stackoverflow.com/questions/5613834/convert-string-to-variable-name-in-javascript
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);
}
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.
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.