Turf: Find nearest position on a linestring

Created on 13 Apr 2018  路  5Comments  路  Source: Turfjs/turf

Is there a way to determine the nearest position on a linestring to a given point? I'm looking to snap a point to its closest position on a line.

nearestPointOnLine returns the nearest vertex while pointToLineDistance returns the distance to the nearest position, but not the actual coordinate.

Most helpful comment

Oh hell, I just figured it out. Turf uses Long/Lat, and Leaflet uses Lat/Long.

All 5 comments

Hi @avinmathew

nearestPointOnLine doesn't always returns a vertex, I think the example on the website just happens to do so. Have you tried using it yet or were you just looking at the example?

Thanks,

You're correct, it does return a point in the geometry.coordinates of the return value. I got caught up in the properties section that I missed it.

Thanks.

I'm having a similar issue- I'm only getting results that return the nearest vertex, not the nearest point on a line.

I basically copied the example:

let line = turf.lineString(outline)
let pt = turf.point([event.layer._latlng.lat, event.layer._latlng.lng])
let snapped = turf.nearestPointOnLine(line, pt)

and snapped returns one of the coordinates in outline

outline is:

[
  [37.33292431975684, -121.8855079589412],
  [37.332557495875015, -121.88629116397354],
  [37.332199201052006, -121.88605512958024],
  [37.33256602668332, -121.88521828036758]
]

The lat/lng for the point is:

[ 37.330305508499606,  -121.8795132637024 ]

and then I use snapped.geometry.coordinates, as it's the only pair of coordinates being returned. Every time it turns out to be one of the coordinates from outline.

Something I noticed when I put my numbers into a fiddle for demonstrating this function is that it's waaaay off.

Compare a jsfiddle with real numbers that we'd use here: https://jsfiddle.net/wishinghand/jeb1o72p/2/

and one with numbers I had to tweak in order for it not to be in Antarctica: https://jsfiddle.net/wishinghand/mjtz6yLc/10/

Oh hell, I just figured it out. Turf uses Long/Lat, and Leaflet uses Lat/Long.

Was this page helpful?
0 / 5 - 0 ratings