假设我有一些重叠的图层,每个图层都有一个点击事件.当我点击地图时,我想知道点击了哪些图层,尽管点击事件在第一层之后停止并且不会传播到其底层.我怎样才能做到这一点?
这是一个示例小提琴及其代码:https://jsfiddle.net/r0r0xLoc/
<div id="mapid" style="width: 600px; height: 400px;"></div>
<script>
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
maxZoom: 18,
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
'<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="http://mapbox.com">Mapbox</a>',
id: 'mapbox.streets'
}).addTo(mymap);
L.polygon([
[51.509, -0.08],
[51.503, -0.06],
[51.51, -0.047]
]).addTo(mymap).on('click', function() {
console.log('clicked on 1st polygon')
});
L.polygon([
[51.609, -0.1],
[51.503, -0.06],
[51.51, -0.047]
]).addTo(mymap).on('click', function() {
console.log('clicked on 2nd polygon')
});
</script>
如果单击每个多边形,则会看到其相关消息.如果单击重叠部分,则只能看到第二个多边形的消息.
解决方法:
您必须直接监听地图“点击”事件并“手动”确定哪些图层包含点击的位置.
例如,您可以使用leaflet-pip插件(多边形点)进行此确定:
map.on("click", function (event) {
var clickedLayers = leafletPip.pointInLayer(event.latlng, geoJSONlayerGroup);
// Do something with clickedLayers
});
演示:https://jsfiddle.net/ve2huzxw/526/(听“mousemove”而不是“click”)