I have a geojson layer named mapLayers and another geojson layer named lmiCounties, with a dropdown list with an item with the id lmiCounties. I want the second layer added to the first, which has already been added to the map when a user clicks on this item, and I want to do this with a function since I will have several layers/list items. The click capture is fine, its just that layer[0] (lmiCounties) does not associate with the actual lmiCounties geoJson layer. Seems like I am missing something simple here.
var lmiCounties = L.geoJson('some data');
document.getElementById('chooser').addEventListener("click", function(e) {
mapLayers.clearLayers();
layer = [e.target.id];
console.log(layer[0]);
mapLayers.addLayer(layer[0]);
e.preventDefault();
});
2 Answers 2
the variable layer will contain the e.target.id which is not a layer, I presume you have a table named layer somewhere and you want to get the layer with the index e.target.id
to do so:
var index=e.target.id;
layer[index].addTo(mapLayers);
If this is actually what you want to make
-
Well sort of...I have several L.geoJson layers, and just want to add them to the L.geoJson mapLayers layer based on a value/id of the clicked element. I want to do something like this example but cant get it to work.Malcolm– Malcolm2016年07月13日 15:39:54 +00:00Commented Jul 13, 2016 at 15:39
-
that example isn't working but I get what you want to do, you can add all your layers and then toggle their visibility with : yourMap.removeLayer(layer[index]); or yourMap.addLayer(layer[index]);Hicham Zouarhi– Hicham Zouarhi2016年07月13日 15:46:13 +00:00Commented Jul 13, 2016 at 15:46
-
I guess I'm not understanding. I'm working on a fiddle to see what's going on. In the example I gave above he captures the leaflet layer using the string value given to the input box with layerClicked = window[event.target.value], however when I replace his value with my layer name, it is undefined.Malcolm– Malcolm2016年07月13日 16:15:20 +00:00Commented Jul 13, 2016 at 16:15
The layer that is to be toggled needs to be a global variable, thus making it available to the window[ ] object see here. I was creating the layer inside a function. I simply created the empty variables at the beginning of the script and it works.
document.getElementById('chooser').addEventListener("click", function(e) {
mapLayers.clearLayers();
layer = window[e.target.id];
console.log(layer._leaflet_id);//to check if it is capturing the map layer
mapLayers.addLayer(layer);
e.preventDefault();
});