![](/img/trans.png)
[英]How do I return details about a geojson polygon on click in Leaflet?
[英]How can I detect a click on the edge of a polygon with Leaflet?
情况:我有一个Leaflet地图(带有Leaflet.draw)。 在此地图上,添加了各种几何形状(点,线,多边形)作为geoJson(使用L.geoJson)。 每个几何都有一个单击处理程序。
问题:当某人在多边形内单击时,将触发click事件。
解决方案:我只希望在单击多边形边缘(闭合多段线)时触发click事件。 一种解决方法是检测点击到边缘的距离。
我找不到为此的书面解决方案。 将不胜感激。
在忽略@chrki的答案的同时开始这个答案,我的是类似的,但结果却有所不同,使用更少的逻辑和更少的层。 所以我认为我会把它扔在这里很好。
如前所述,Leaflet中无法检测到edgeclick。 将事件附加到功能后,它会在整个元素上做出响应。 您可以做的是双击功能,在geojson图层生成的多边形的顶部放置一条折线,然后将侦听器附加到折线而不是多边形。
// Create geojson layer w/o adding data
var geojson = new L.GeoJSON(null, {
// Don't draw the stroke
style: function () {
return {
stroke: false
}
},
onEachFeature: function (feature, layer) {
// Check if layer is a polygon
if (layer instanceof L.Polygon) {
// Fetch coordinates from polygon
var latLngs = layer.getLatLngs();
// Push first coordinate to complete line
latLngs.push(latLngs[0]);
// Create polyline using coordinates
var polyline = new L.Polyline(latLngs);
// Add click listener
polyline.on('click', function () {
alert('Polyline clicked!');
});
// Add polyline to featuregroup
polyline.addTo(featureGroup);
}
}
}).addTo(map);
// Create featuregroup, add it to the map
var featureGroup = new L.FeatureGroup().addTo(map);
// Test
geojson.addData({
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [[
[-45, -45],
[-45, 45],
[45, 45],
[45, -45],
[-45, -45]
]]
}
}]
});
在Plunker上的工作示例: http ://plnkr.co/edit/d1tLOIEeBPsv7YFDWavA?p=preview
我想到的一种方法是用相同的坐标创建一条附加的折线,并将其放在多边形的顶部,并使多边形不可单击。 这将需要为使用onEachFeature
创建GeoJSON功能添加一些逻辑。
Leaflet的多边形(和折线)是由单个SVG元素组成的,我不确定是否可以在不做一些Javascript数学运算或类似操作的情况下检测到外部边缘上的点击, onclick
事件只是附加到整个元素上。
var polyoverlay = new L.featureGroup().addTo(map);
var edgeoverlay = new L.featureGroup().addTo(map);
var geojsonobj = {"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": {"type": "Polygon", "coordinates": [[[-87.027648, 20.820875 ], [-87.027648, 21.320875 ], [-86.527648, 21.320875 ], [-86.527648, 20.820875 ], [-87.027648, 20.820875 ] ] ] } } ] };
var poly = L.geoJson(geojsonobj, {
onEachFeature: function(feature, layer){
// latitude/longitude to longitude/latitude coordinates
var lonlats = [];
feature.geometry.coordinates[0].forEach(function(f){
lonlats.push([f[1], f[0]]);
});
// add polyline to map
var polyline = L.polyline(lonlats,{
color: 'black'
}).bindPopup('hello').addTo(edgeoverlay);
// add polygon to map
var polygon = L.polygon(lonlats,{
color: 'blue',
clickable: false
}).addTo(polyoverlay);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.