[GIS] Leaflet dynamic legend for active layer controls

layer-controllayersleafletoverlay

I´m trying to achieve a map legend that shows the names of the active Layers and also adds new names to the list every time a new layer is checked.

Also it should only appear when at least one layer is active and disappear when no layer is checked.

Right now I´m pretty close to my goal I think but something is still not working correctly and I don´t know what it is.

var arr = new Array ();

var layerLegend = L.control({position: 'bottomleft'});

layerLegend.onAdd = function (map) {
var div = L.DomUtil.create('div', 'legend');
div.innerHTML +=
'<b>Legende</b></br>'+test();
return div;
};

map.on('overlayadd', function (arr, eventLayer) {
        arr.push(eventLayer.name);
        layerLegend.addTo(map); 
}
);

function test (arr) {
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}};



map.on('overlayremove', function (eventLayer) {
    map.removeControl(layerLegend);
}
);

Best Answer

There are some errors in your JS code.

First, you define the function test(arr) with an argument but forgot to put this argument when you call the function test.

Second, console.log print its argument to the web console but does not print to your HTML page. You may use this to make it working:

function test (arr) {
  for (var i = 0; i < arr.length; i++) {
  //console.log(arr[i]);
  return arr[i];
}};