Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically collapse Leaflet JS layer control

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.

like image 549
fnllc Avatar asked Jul 07 '14 13:07

fnllc


2 Answers

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")
like image 97
Patrick D Avatar answered Oct 22 '22 22:10

Patrick D


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.

like image 1
adrien Avatar answered Oct 22 '22 23:10

adrien