I would like to have the name of a layer used by Leaflets layer control feature come from a variable instead of a string and based on data from the layer. The example shown below uses the variable layerName.
Is this even possible since it is expecting a name value pair? Is there a work around?
var layerName = feature.properties.condition[0];
//layer control
var baseMaps = {
"OpenStreetMap": OSM,
"Aerial Imagery": MapQuestOpen_Aerial
};
var overlayMaps = {
layerName: layer1,
};
L.control.layers(baseMaps, overlayMaps).addTo(map);
1 Answer 1
According to the Leaflet documentation, the layer config is an object literal with layer names as keys and layer objects as values.
That means you can use []
to set the object key, here is the modified codes:
var layerName = feature.properties.condition[0];
//layer control
var baseMaps = {
"OpenStreetMap": OSM,
"Aerial Imagery": MapQuestOpen_Aerial
};
//create the layer config object first
var overlayMaps = {
//layerName: layer1,
};
//add the layer to the overlayMaps with a dynamic layer name
overlayMaps[layerName] = layer1;
L.control.layers(baseMaps, overlayMaps).addTo(map);