5

How can the Leaflet JS layer control be closed using JS code? On desktop, the control closes nicely when the mouse cursor leaves the control. However, on mobile phones, the user needs to tap outside the control to close it. I would like to manually close it once a user selects a layer inside the control.

fnllc
  • 3,047
  • 4
  • 25
  • 42

2 Answers2

5

The state of this control is controlled by the leaflet-control-layers-expanded class. If you add or remove this class to the leaflet-control-layers element, then you can control the state.

These examples use jQuery for simplicity.

To expand the control:

$(".leaflet-control-layers").addClass("leaflet-control-layers-expanded")

To collapse the control:

$(".leaflet-control-layers").removeClass("leaflet-control-layers-expanded")
Patrick D
  • 6,659
  • 3
  • 43
  • 55
  • How would you do this so when the user clicks the toggle icon, it will expand, and then when he clicks it again, it will collapse? – redshift Jan 22 '16 at 13:57
  • The issue is still behind discussed [here](https://github.com/Leaflet/Leaflet/issues/2713). Basically, there's no good option here, if you are going to listen to changes to the layer control form's `input` fields and then call he removeClass above, your user will have to re-open every time they tap an option, which is cumbersome if you want to select/deselect several layers. What I currently do is to add a close button to the form if the browser is mobile/touch (user `L.Browser`). See my reply below. – adrien Feb 12 '16 at 11:48
1

For mobile devices, I would simply add a close button to the div and then use js to change the class as mentioned above:

Note that I changed the leaflet source code here but it should be feasible externally as well. Add the following code before the line container.appendChild(form); in your leaflet source - tested with 0.7.7)

if (L.Browser.android || L.Browser.mobile || L.Browser.touch || L.Browser.retina) {
    var yourCloseButton = this.yourCloseButton = L.DomUtil.create('div', className + '-close');
    this.yourCloseButton = L.DomUtil.create('div', className + '-close', form);
    this.yourCloseButton.innerHTML = '<button class="btn-close-layers-control">X</button>'; 
L.DomEvent.on(this.yourCloseButton, 'click', this._collapse, this);  
} 

`Then position the button with css.

adrien
  • 504
  • 1
  • 7
  • 17