問題描述
假設我有一些重疊的圖層,每個圖層都有一個點擊事件.當我點擊地圖時,我想知道點擊了哪些圖層,盡管點擊事件在第一層之后停止并且不會傳播到其底層.我怎樣才能做到這一點?
Let's say I have some overlapping layers and each layer has a click event. When I click on the map, I'd like to know which layers are clicked on, though the click event stops after the first layer and does not propagate to its underlying layers. How can I achieve this?
這是一個示例小提琴及其代碼:https://jsfiddle.net/r0r0xLoc/
Here's a sample fiddle and its code: 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 >OpenStreetMap</a> contributors, ' +
'<a +
'Imagery ? <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>
如果您單擊每個多邊形,您會看到其相關消息.如果單擊重疊部分,您只會看到第二個多邊形的消息.
If you click on each polygon, you see its related message. If you click on the overlapping part, you only see the message for the second polygon.
推薦答案
您必須直接監聽地圖 "click"
事件并手動"確定哪些圖層包含點擊位置.
You have to listen directly to the map "click"
event and to "manually" determine which layers contain the clicked position.
您可以使用 leaflet-pip 插件(點在多邊形中)例如進行此確定:
You can use leaflet-pip plugin (point in polygon) for example for this determination:
map.on("click", function (event) {
var clickedLayers = leafletPip.pointInLayer(event.latlng, geoJSONlayerGroup);
// Do something with clickedLayers
});
演示:https://jsfiddle.net/ve2huzxw/526/(聽"mousemove"
而不是 "click"
)
Demo: https://jsfiddle.net/ve2huzxw/526/ (listening to "mousemove"
instead of "click"
)
這篇關于傳單事件:如何傳播到重疊層的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!