Turfjs / turf

A modular geospatial engine written in JavaScript and TypeScript
https://turfjs.org/
MIT License
9.22k stars 935 forks source link

nearestPointOnLine uses wrong calculation #1878

Open manly opened 4 years ago

manly commented 4 years ago

https://github.com/Turfjs/turf/blob/master/packages/turf-nearest-point-on-line/index.ts

This code is wrong. It is an approximation.

You calculate the azimuth (bearing/direction) between p1 and p2, and from that azimuth, you try to make a perpendicular great circle by changing that azimuth by +180 (or -180, whatever). The problem with this is that, as you move along the path from p1 to p2, your azimuth constantly changes, assuming you are taking the shortest great-circle distance (ie: Haversine/Vincenty). Unless you use a line that assumes the azimuth does not change (ie: occasionally used for moving by sea), your azimuth only applies for p1. p2 has a different azimuth, and so does every single point along that great-circle.

It is a decent approximation of an answer for short distances, but know that this calculation will be way* off if distance(p1, p2) is either long, or if you're close to true north/south pole.

If you do have the proper code for this, I would welcome you let me know.

Thanks

-Phil

rowanwins commented 4 years ago

Thank you for the description of the issue @manly

This module is in need of a bit of an overhaul - there are number of reported issues with it.

THere are perhaps some interesting ideas here which could be adapted https://stackoverflow.com/questions/16429562/find-a-point-in-a-polyline-which-is-closest-to-a-latlng

smallsaucepan commented 1 year ago

Hi @JamesLMilner @rowanwins @twelch . Will take a look at this if you'd like to assign my way.