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:
light.setVisibility(false);
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) {
map.addControl(button);
} else {
map.removeControl(button);
}
});
}());
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.
Best Answer
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:
If you also need to change the position of your legend, you can play with the CSS properties to place it where you want.