turf icon indicating copy to clipboard operation
turf copied to clipboard

nearestPointOnLine can return wrong endpoint when the target point is very far from the line

Open mlc opened this issue 8 months ago • 3 comments

Given a LineString like this, with one endpoint in the North Atlantic ocean and one in the South Pacific:

{
  "type": "Feature",
  "properties": {},
  "geometry": {
    "type": "LineString",
    "coordinates": [
      [-96.80974, -58.32062],
      [-50.2464, 38.36643]
    ]
  }
}

and a target Point like this, in Europe,

{
  "type": "Feature",
  "properties": {},
  "geometry": {
    "type": "Point",
    "coordinates": [13.6023, 46.50646]
  }
}

the nearestPointOnLine function should return [-50.2464, 38.36643], the segment endpoint in the North Atlantic ocean, as it is much closer than the other endpoint (5173km vs 15348km), and no other point on the segment is closer.

However, instead, turf returns a point very close to (withing floating-point-precision error of) the South Pacific endpoint.

mlc avatar Apr 22 '25 21:04 mlc

Thanks for picking this up @mlc. Yes, that's definitely not working in the case you've found. Before we press ahead with your PR would you mind if I do a little debugging of the current vector code? Would like to understand why that isn't working.

smallsaucepan avatar Apr 28 '25 11:04 smallsaucepan

Thanks for having a look, @smallsaucepan! Obviously if you have a better solution than mine I am not offended if you take that instead!

mlc avatar Apr 28 '25 17:04 mlc

For what it's worth, the only debugging hint I can offer is very small: the failing test case I provide fails even if you swap the order of the points on the input LineString, so it doesn't appear that the bug is e.g. preferring the first point to the second in certain circumstances.

mlc avatar Apr 28 '25 17:04 mlc