1

I want to toggle the Leaflet layer control when the user clicks in a button.

var layerControl = L.control.layers(
  {
    '<i class="fas fa-map-marked"></i>': OSM,
    '<i class="fas fa-image"></i>': Esri_WorldImagery
  }, null, {collapsed: false}
).addTo(map);

<button onclick="toggleLayerControl()">toggle control</button>

function toggleLayerControl(){
   if(layerControl.display=="block"){
      layerControl.display = "none";
   }else{
      layerControl.display = "block";
   }
}

What's the simplest way of doing that?

2

The functionality is built in into Leaflet. E.g.:

if(layerControls.collapsed) {
  layerControls.expand();
} else {
  layerControls.collapse();
}

To toggle visibility of the layer control in the map use:

layerControls.addTo(map)    
layerControls.remove()

Check out the documentation for more info and details.

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.