New Bee New Bee - 1 month ago 16
Javascript Question

Finding shortest path in leaflet

I have collection of points within line on map using L.pather plugin. Also I have markers populated on map. Given any two markers, I want to find the shortest distance(path) on the map on the previous provided line . Attached is image for reference.

enter image description here

Here I want to draw a line between A and B on the given path (blue line). Blue dots on line are the collection of point (lat,lng) that I have. Is there any way I can do that ?

iH8 iH8
Answer

You could use the distanceTo method of L.LatLng to calculate the distance from your L.Marker's latlng to each latlng of your polyline:

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
}

If you calculate that for each marker, you can use the spliceLatLngs method of L.Polyline to trim the polyline to those points:

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: