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.
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")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With