在以下最小示例中,我的问题可以重现:
https://leafletjs.com/examples/layers-control/example.html
当您在触摸设备上打开网站或在桌面上模拟触摸事件,然后点击右上角的控件时,它将打开,而在地图上点击后,它将再次关闭。 预计会有很多,但是当控件打开时单击标记时,会弹出弹出窗口,但控件不会关闭。
在示例中这无关紧要,但是在我的应用程序中,大多数地图都是由带有弹出窗口的折线组成的,这使移动用户很难关闭控件,因为他们必须在所有折线之外点击才能使控件起作用。
是否可以配置Leaflet(或事件处理程序)以关闭弹出窗口上的控件?
答案 0 :(得分:0)
您可以将城市变量分配给L.featureGroup
,然后通过删除指示扩展控件的.leaflet-control-layers-expanded
类来监听onclick事件,同时点击标记。
var cities = L.featureGroup();
...
cities.on('click', function() {
document.getElementsByClassName('leaflet-control-layers')[0]
.classList.remove('leaflet-control-layers-expanded');
})
<!DOCTYPE html>
<html>
<head>
<title>Layers Control Tutorial - Leaflet</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" />
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.3.4/dist/leaflet.js" integrity="sha512-nMMmRyTVoLYqjP9hrbed9S+FzjZHW5gY1TWCHA5ckwXZBadntCNs8kEqAWdrb9O7rxbCaA4lKTIWjDXZxflOcA==" crossorigin=""></script>
<style>
html, body {
height: 100%;
margin: 0;
}
#map {
width: 600px;
height: 400px;
}
</style>
</head>
<body>
<div id='map'></div>
<script>
var cities = L.featureGroup();
L.marker([39.61, -105.02]).bindPopup('This is Littleton, CO.').addTo(cities),
L.marker([39.74, -104.99]).bindPopup('This is Denver, CO.').addTo(cities),
L.marker([39.73, -104.8]).bindPopup('This is Aurora, CO.').addTo(cities),
L.marker([39.77, -105.23]).bindPopup('This is Golden, CO.').addTo(cities);
var mbAttr = 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
'<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
mbUrl = 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw';
var grayscale = L.tileLayer(mbUrl, {id: 'mapbox.light', attribution: mbAttr}),
streets = L.tileLayer(mbUrl, {id: 'mapbox.streets', attribution: mbAttr});
var map = L.map('map', {
center: [39.73, -104.99],
zoom: 10,
layers: [grayscale, cities]
});
var baseLayers = {
"Grayscale": grayscale,
"Streets": streets
};
var overlays = {
"Cities": cities
};
L.control.layers(baseLayers, overlays).addTo(map);
cities.on('click', function() {
document.getElementsByClassName('leaflet-control-layers')[0]
.classList.remove('leaflet-control-layers-expanded');
})
</script>
</body>
</html>