Take the 2-minute tour ×

I'm using the Leaflet mapping API. I would like to determine which point in a polyline has been clicked on. The polyline is one that I have rendered using the Directions services from MapQuest Open.

The relevant code is:

for ( var i = 0; i < latlngs.length; i++ )

   // the equals method uses a small fudge factor to decide if the two 
   // points are the same.

   if ( latlng.equals( latlngs[ i ] ))
      return i;

.equals() is supposed to compare points with a fudge factor. When I click on the polyline I get an event with lat/lngs like:


My lat/lngs in the polyline are of less precision as in:


So as I loop through looking for a match equals() never returns true. Clearly, the click event is firing, so leaflet knows I've clicked the polyline, but there doesn't seem to be a clean way of getting the actual offset of the latlng that was clicked on.

I'm considering just reducing the precision returned from the mouse click, but that doesn't "feel" like the right solution.

Any help/pointers would be greatly appreciated.


Setting L.LatLng.MAX_MARGIN to 1.0E-3 seems to work but that seems like a very coarse margin.

share|improve this question
The click probably lies somewhere on a segment between two points. Try using L.LineUtil.pointToSegmentDistance() –  flup Apr 24 at 22:57
Mhm... I see it calculates in points, not latlngs –  flup Apr 24 at 23:08
add comment

1 Answer

I've come up with an solution that is probably not coture but seems to work. I notice that there is a _originalPoints array in the polyline. There is also layerPoint member in the polyline event that is a Point object.

I'm not a fan of using undocumented APIs but looping through the points finding the closest point to the clicked point, using the L.LineUtil.pointToSegmentDistance seems to work as in:

    var point = e.layerPoint;

var points = polyline._originalPoints;


    if ( i < points.length - 2 )

        if ( min_distance > L.LineUtil.pointToSegmentDistance( point, points[i], points[ i + 1] ) )
            min_distance = L.LineUtil.pointToSegmentDistance( point, points[i], points[ i + 1] );
            min_offset = i;


share|improve this answer
add comment

Your Answer


