我们说我有一些重叠的图层,每个图层都有一个点击事件。当我点击地图时,我想知道点击了哪些图层,尽管点击事件在第一个图层之后停止并且不会传播到其底层图层。我怎样才能做到这一点?
这是一个示例小提琴及其代码: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>
如果单击每个多边形,则会看到其相关消息。如果单击重叠部分,则只能看到第二个多边形的消息。
答案 0 :(得分:7)
您必须直接聆听地图"click"
事件并聆听&#34;手动&#34;确定哪些图层包含点击的位置。
例如,您可以使用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"
)
答案 1 :(得分:0)
有一个传单插件,用于将事件传播到底层:https://github.com/danwild/leaflet-event-forwarder
您可以在JavaScript中使用它来启用事件转发,例如:
const myEventForwarder = new L.eventForwarder({
map: map,
events: {click: true, mousemove: false}
});
答案 2 :(得分:0)
问题在于添加层(几何图形)的顺序。就我而言,我有一个几何数组,我所做的只是使用其边界 L.LatLngBounds#contains
对几何数组进行排序,因此如果一个几何包含另一个,则应稍后添加。
var geometries = [layerOne, layerTwo, ...];
geometries
.sort((a, b) => {
// in my case a separate function is required because the geometry could be a Circle, Rectangle, Polygon or Marker
// and the methods to get the corresponding bounds are different.
var boundsA = this.getBoundsFromGeometry(a);
var boundsB = this.getBoundsFromGeometry(b);
// if the second geometry contains the first, the order must be change so the layers don't overlap
return boundsB.contains(boundsA) ? 1 : -1;
})
.forEach(l => this.map.addLayer(l));