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);
up vote 2 down vote accepted

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); 

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.