I'm having difficulties making my legend control work. I've loaded 3 WMS layers from Geoserver and declared their legends. I grouped the layers as Overlays and I have 2 basemaps. I found a code and adapted it as below to make a switch between the legends.What this does now is only displays Legend2. In all the examples I've seen online, the layers (be it declared as baselayers or overlays) do not overlay in the app, but are removed upon another layer selection.

Does this function work only for layer removal or should it work in my case too, and I'm missing something?

var overlayMaps = {
  "DropOut_Rates": DropOUT,
  "Schools": Schools    

currentLegend = legend2;

map.on('overlayadd', function (eventLayer) { 

  if (eventLayer.name === 'DropOut_Rates') { 
    currentLegend = legend2; 
  else if (eventLayer.name === 'UAT3') { 
    currentLegend = legend3; 
  else if (eventLayer.name === 'Schools') { 
    currentLegend = legend1; 

1 Answer 1


I found a code and adapted it as [shown] below

General piece of advice: Do not copy-paste code and expect it to work. Make an effort to understand what the code does, and why.

There is information missing from your code snippet. I'm seeing you're using a overlayadd map event, which according to the documentation fires when the user interacts with a layers control (an instance of L.Control.Layers).

Do you have a layers control in your code? How does its initialization look like? Does the overlayadd event fire when expected? What is the value of eventLayer in the event handler (use your browser's debugging capabilities)?

  • Hi Ivan. Thanks for the reply. I do have layers control. As mentioned, I have 2 basemaps and several overlays. //Add both layer groups to map L.control.layers(baseMaps, overlayMaps).addTo(map) The overlayadd event doesn't seem to trigger, the code seems to stop at legend2.addTo(map)
    – CIv
    Dec 14, 2016 at 17:43

Your Answer

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

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