Reputation: 2785
In my project, when I load a page I pull a list of overlay names from the database, these are stored in a JS Array.
Using the default code below, how do I fill the overlayMaps with contents from an array rather than hard coding what the values will be:
var overlayMaps = {
"Cities": cities,
"Towns": towns
};
So as an example, instead of creating overlayMaps with the hard coded values Cities & Towns, I need to pull these values from an array that gets its data from the DB, The array in leymans terms might look like this under the hood:
[ "MyValue1": myvalue1,"MyValue2": myvalue2, "MyValue2": myvalue2,] etc
Maybe I need to create a dictionary, although I have no experience doing this in JS, only in C#
Am using guide: https://leafletjs.com/examples/layers-control/
Upvotes: 0
Views: 1057
Reputation: 2785
Solution:
Reading the leaflet API instructions, you can actually add a single item to an L.control one at a time using the command addOverlay( layer, name). Adds an overlay (checkbox entry) with the given name to the control. For demo purposes below, I'm using the same value var cities for each of the three checkboxes, but to show how we add the individual items from the array, we're looping through this array and adding the items one at a time.
var littleton = L.marker([39.61, -105.02]).bindPopup('This is Littleton, CO.'),
denver = L.marker([39.74, -104.99]).bindPopup('This is Denver, CO.'),
aurora = L.marker([39.73, -104.8]).bindPopup('This is Aurora, CO.'),
golden = L.marker([39.77, -105.23]).bindPopup('This is Golden, CO.');
var cities = L.layerGroup([littleton, denver, aurora, golden]);
var places = new Array()
places.push("Cities");
places.push("Towns");
places.push("MyPlaces");
var lControl = L.control.layers(null, null);
lControl.addTo(map);
places.forEach(myFunction);
function myFunction (item) {
lControl.addOverlay(cities, '' + item + '');
}
Upvotes: 1