Leaflet / Mapbox - Drag & Drop
我有一个使用Mapbox / Leaflet JS API的基于Web的地图。
在地图上,我有几个固定的标记和其他标记,这些标记是根据推送到浏览器的GPS数据移动的。当将活动标记放到固定标记上时,我想确定所涉及的两个标记。
我已经为移动标记的" dragend "事件实现了一个处理程序,使我能够识别被拖放的标记。
我的问题是,如何识别放置在其上的标记?
这很难做到,因为唯一可以正确识别标记的是它的纬度/经度位置。因此,如果您尝试将标记放到纬度/经度为0,0的标记上,则需要将其精确地放置在该位置上,这将是一件非常困难的事情。
您当然可以在其中建立某种容忍度,但是该容忍度将需要根据缩放级别而变化,我认为很难做到这一点。您可以执行以下操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | // Drag has ended marker.on('dragend', function (e) { // Get position of dropped marker var latLng = e.target.getLatLng(); // Object to hold nearest marker and distance var nearest = {}; // Loop over layer which holds rest of the markers featureLayer.eachLayer(function(layer) { // Calculate distance between each marker and dropped marker var distance = latLng.distanceTo(layer.getLatLng()); // Set the first as nearest if (!nearest.marker) { nearest.marker = layer; nearest.distance = distance; // If this marker is nearer, set this marker as nearest } else if (distance < nearest.distance) { nearest.marker = layer; nearest.distance = distance; } }); }); |
Plunker上的示例:http://plnkr.co/edit/GDixNNDGqW9rvO4R1dku?p=preview
现在,
因此,现在您有了最接近的标记,并且它到放下的标记的距离可以实现公差,大致如下:
祝您好运,希望对您有帮助