Leaflet – How to Get Polyline Coordinates in Leaflet

leafletline

Using leafletjs, I created a polyline connecting a bunch of markers:

var line = L.polyline( latlngs, {
  weight: 5,
  color: '#8EE9FF'
})

Now, I am trying to get the start and end markers when I click on a polyline:

line.on('click',(e)=>{
  // get starting marker
  // get ending marker
})

Looking at e, I see the entire list of latlgns but I just need 2 for the line segment I clicked on. Is it not possible? Should I create multiple separate lines instead?

Best Answer

The below code uses Leaflet.GeometryUtil to check whether the clicked LatLng is on a segment and then populates start and end variables with the respective LatLngs of that segment.

line.on("click", (e) => {
  let i = 0,
    start = {},
    end = {}
  const verts = e.target.getLatLngs() // verts...vertices of polyline

  //Loop through vertices while there is one at index i + 1
  while (verts[i + 1]) {
    //belongsSegment returns a Boolean
    const segmentFound = L.GeometryUtil.belongsSegment(e.latlng, verts[i], verts[i+1])
    if (segmentFound) {
      start = verts[i]
      end = verts[i + 1]
      break
    }
    i++
  }
});