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:

  // 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?

  • Welcome to gis.SE! Could you provide a jsfiddle (or similar) so that others can test your map? – Stefan Dec 27 '18 at 11:33
  • 1
    Actually, we require that the relevant code snippet be placed in the body of the question. Fiddles are all well and good, but if it's external to Stack Exchange, it's ephemeral, and therefore likely to damage the question when it disappears. – Vince Dec 27 '18 at 12:16

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]
|improve this answer|||||
  • Thanks Stefan. I ended up using multiple lines already and that works but your answer looks correct. – simon tan Dec 27 '18 at 22:43
  • Interesting - It messes up when having multiple parallel lines in different length – BananaAcid Mar 9 at 22:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.