在Leaflet中寻找最短路径

3

我使用L.pather插件在地图上收集了一系列在线上的点。同时,我在地图上放置了标记。给定任意两个标记,我想要找到先前提供的线路上地图上最短的距离(路径)。附带参考图片。

enter image description here

我想在给定的路径(蓝线)上在A和B之间画一条线。蓝线上的蓝点是我的点集合(纬度,经度)。有没有办法做到这一点?


дҪ е°қиҜ•иҝҮдҪҝз”ЁdistanceTo(http://leafletjs.com/reference.html#latlng-distanceto)жқҘе®һзҺ°дҪ жғіиҰҒзҡ„еҠҹиғҪдәҶеҗ—пјҹ - snkashis
1个回答

2
你可以使用 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方法将折线修剪为这些点:

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)

Reference:


太好了。你很棒 @iH8。非常感谢 :) 。你能否也帮忙回答我的之前的问题:https://dev59.com/zpDea4cB1Zd3GeqPZUQ5 - New Bee
给定一个latlng数组。我能在leaflet中获取两个节点之间的最短路径吗? - New Bee
我发布的函数遍历了一个包含'L.LatLng'对象(来自折线)的数组,并测量每个到另一个'L.LatLng'对象(来自标记)的距离。如果您想对包含坐标数组的数组进行相同的操作,需要先将它们转换为'L.LatLng'对象,以便您可以使用'L.Latlng'的'distanceTo'函数。或我误解了您的最新评论吗?至于第一条评论,不用了 :)欢迎随时光临。我会尽快查看的。我怀疑是个bug:( - iH8

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接