Distance to Polygon / MultiPolygon from Point
See original GitHub issueOpened new issue as requested by @rowanwins from #252 .
Currently there is no native way to achieve distance to Polygon (and Multi-Polygon) from a point using Turf.
There was a suggestion in the previous issue to use the vertexes and measure the distance to those, but we end up with the following issue:
In this image, B is clearly the closest point to the polygon, but using the above algorithm we’d end up with point A.
I’ve come up with the following solution for now:
const distanceKm = pointToLineDistance(point, polygonToLineString(polygon));
if (booleanPointInPolygon(point, polygon)) {
return distanceKm * -1;
} else {
return distanceKm;
}
Using this over an array of Polygons allows me to achieve what I want. (I want to compare the distances of an array of Polygons to a Point and pick out the one which is the closest).
Still need to add support for MultiPolygon
s (as polygonToLineString
doesn’t support them) - but that’s as easy as splitting the geometry’s coordinate array into multiple regular Polygons
and finding the shortest distance within that group and choosing the shortest.
Since there is no direct function for Polygons, it makes use of polygonToLineString()
to convert them to lines first and run the distance checks on that.
If the point is inside the Polygon, I return the negative value of the distance (how far inside the polygon the point is).
Issue Analytics
- State:
- Created 4 years ago
- Reactions:8
- Comments:11 (1 by maintainers)
Top GitHub Comments
Seems to work nicely. Thank you @lostpebble !
In case someone sees this and just wants to use it in place without having to recompile turf, this version works with turf ~5.1.6:
Thanks for sharing your code @lostpebble and @pachacamac 🙌 I made a typescript version of the function if anyone would want to copy-paste it.