I'm new to Leaflet/Javascript and have been struggling to get legends a map to show only when a specific layer is selected from the layer control. I have three layers, one of which I would like to have no legend and two others that have a corresponding legend. I came across an example, but have not been able to make it work:

// Add and remove legend from layers
map.on('overlayadd', function (eventLayer) {
// Switch to the Permafrost legend...
   if (eventLayer.name === 'Permafrost') {
  else { // Or switch to the treeline legend...

I created a jsfiddle with the specific example:


  • Please explain more specifically how your example fails to work.
    – whuber
    Apr 7, 2014 at 21:52
  • The example I have on jsfiddle has the default view on a layer called "Satellite" and has the two legends showing. What I would like to do is have an action to add and remove specific legends when you select the layers from the Layer Control . On the specific example I want my "Satellite" layer to contain no legend, and when I select "Permafrost" I want only legend2 to show map, and when I select "Treeline", I want only legend1 to show on the map. The current code does not do any of the above and has both legends on all layers. Apr 7, 2014 at 22:09

1 Answer 1


You've defined your layers as baselayers (not overlays) and so you'll want to change overlayadd to baselayerchange

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

should be

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

Here's a fork of your original jsFiddle that demonstrates this change - http://jsfiddle.net/ry9zf/2/

Your Answer

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

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