admin管理员组

文章数量:1386636

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.

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.

Share Improve this question asked Jul 7, 2014 at 13:38 fnllcfnllc 3,1374 gold badges28 silver badges47 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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")

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.

本文标签: javascriptProgrammatically collapse Leaflet JS layer controlStack Overflow