L.LatLng
的 distanceTo
方法来计算从你的 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.Polyline
的spliceLatLngs
方法将折线修剪为这些点:
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:
distanceTo
(http://leafletjs.com/reference.html#latlng-distanceto)жқҘе®һзҺ°дҪ жғіиҰҒзҡ„еҠҹиғҪдәҶеҗ—пјҹ - snkashis