在传单中寻找最短路径

Finding shortest path in leaflet

我使用 L.pather 插件收集了地图上线内的点。我还在地图上填充了标记。给定任意两个标记,我想在之前提供的行的地图上找到最短距离(路径)。附上图片供参考。

这里我想在给定的路径(蓝线)上在A和B之间画一条线。线上的蓝点是我拥有的点 (lat,lng) 的集合。有什么办法可以做到吗?

您可以使用 L.LatLngdistanceTo 方法来计算从您的 L.Marker 的经纬度到折线的每个经纬度的距离:

function getNearestPointOnPolyline (marker, polyline) {
  var nearestKey,
      nearestDistance,
      markerLatLng = marker.getLatLng(),
      polylineLatLngs = polyline.getLatLngs()

  for (i = 0; i < polylineLatLngs.length; i++) {
    var distance = markerLatLng.distanceTo(polylineLatLngs[i])
    if (!nearestDistance || nearestDistance > distance) {
      nearestKey = i
      nearestDistance = distance
    }
  }
  return nearestKey
}

如果你计算每个标记,你可以使用 L.PolylinespliceLatLngs 方法到 trim 这些点的折线:

var polyline = new L.Polyline([...]).addTo(map),
    marker_a = new L.Marker([...]).addTo(map),
    marker_b = new L.Marker([...]).addTo(map)

// Get key of nearest point on polyline
var nearest_a = getNearestPointOnPolyline(marker_a, polyline),
    nearest_b = getNearestPointOnPolyline(marker_b, polyline)

// Determine start and end key
var start = Math.min(nearest_a, nearest_b),
    end = Math.max(nearest_a, nearest_b)

// Splice all keys untill start key
polyline.spliceLatLngs(0, start)
// Splice all keys from the end
polyline.spliceLatLngs(end - start + 1,polyline.getLatLngs().length)

参考: