I'm currently trying to add a legend to my map and to show/hide it, when the corresponding layer (an image layer) is shown/hidden.
My approach was to add a custom button with a .png of my legend. That worked without problems.

The image layer ("light") is deactivated when loading the map:


Now, I want to show the legend when activating the layer and hide it when deactivating the layer and so on. And that works as well, but only once using these lines:

(function legend() {
    light.events.register("visibilitychanged", light, function() {
    if (light.getVisibility() === true) {
        } else {

I guess i have to reload the function somehow after the button is removed?

All things I tried didn't work and that was the best I was able to come up with.

1 Answer 1


You can use the attribution feature of OpenLayers for this:


This will work accordingly (ie. active/deactivate) with every layer in your map. You'd only need to replace the text with your PNG:

'attribution': "<img src='mylegend.png'/>"

If you also need to change the position of your legend, you can play with the CSS properties to place it where you want.

  • While this will indeed work, it's nice to actually show the attribution too. (Heck, it's even required for most maps I know of.)
    – Arjan
    Oct 17, 2016 at 15:48

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.