2

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);
asked Jul 29, 2015 at 16:33

1 Answer 1

2

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); 
answered Jul 29, 2015 at 17:05

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.