2

Is it possible to add a simple show/hide button on the leaflet map which will allow the user to see the legend on choice?

Here is my code for the legend:

    var legend0 = L.control({});
        legend0.onAdd = function (map) {
    var div = L.DomUtil.create('div', 'info legend'),
    grades = ["Localisation", "Orientation"],
    labels = ["icon-gamze/location1-zoom1.png", "icon-gamze/location2-zoom1.png"];
     div.innerHTML += '<b>Localisation</b><br>' 
for (var i = 0; i < grades.length; i++) {
       div.innerHTML +=
       (" <img src="+ labels[i] +" height='20' width='20'>") + grades[i] +'<br>';
}

       return div;
      };

       legend0.addTo(map);
  • You may achieve this quite easily using jquery .hide() and .show() methods, or using simple vanilla JS functions and CSS. – juminet Mar 20 '17 at 11:06
  • Thanks, but could you please exemplify? I'm quite new to the suite. – Gamze Mar 20 '17 at 11:12
3

For this, you need to write a few lines in Javascript. Many solutions exist, depending if you want to use JS and/or CSS frameworks or not. Here is below an example with jquery:

First, add a button somewhere in your page:

<button type="button" onclick="toggleLegend();">My button</button>

Then, in the function toggleLegend():

    showLegend = true;  // default value showing the legend

    var toggleLegend = function(){
        if(showLegend === true){
        /* use jquery to select your DOM elements that has the class 'legend' */
           $('.legend').hide(); 
           showLegend = false; 
        }else{
           $('.legend').show();
           showLegend = true; 
        }
    }

This target all the elements that have the class 'legend' of your page.

Have a look at e.g. https://stackoverflow.com/questions/21070101/show-hide-div-using-javascript#21070237 for a pure vanilla JS example of show/hide.

J.

  • Thank you @juminet for your answer, but I unfortunately I could not make it work out. Can it be due to the fact that I have a number of legends on my map? – Gamze Mar 20 '17 at 17:19
  • Does it work at least for one legend? Did you include jquery in your page? – juminet Mar 20 '17 at 19:22
  • Yes, I included jquery. And, no I could not make it work for even one legend. @juminet – Gamze Mar 21 '17 at 9:42
  • there was an error in my code. Sorry, I hadn't try it before – juminet Mar 21 '17 at 9:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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