关于Leaflet/地图框:Leaflet/地图框-拖动

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

现在,nearest对象将保留最接近放置位置的标记。最近距离可能会根据您的变焦等级而变化。当您处于缩放级别1时,您似乎已将其精确地放到了另一个标记上,但距离可能有数千英里。缩放比例为18时,差异将小得多,但实际上将其精确地放在相同的经度/纬度上几乎是不可能的。否则,您可以简单地将所有latlng与删除的latlng进行比较,但实际上这是行不通的。

因此,现在您有了最接近的标记,并且它到放下的标记的距离可以实现公差,大致如下:if (nearest.distance < (x / y))其中x是距离,而y缩放级别。这是您需要玩弄才能正确使用的东西。一旦确定了正确的公差,就可以在处理程序中正确实现公差以及进行距离比较。

祝您好运,希望对您有帮助