简体   繁体   中英

Find coordinate of the closest point on polygon in Shapely or GeoPandas

I would like to find the distance from a point to a polygon, but the real near distance

I'm doing the following:

from shapely.geometry import Point, Polygon
import shapely
import shapely.ops
from shapely.ops import nearest_points

coords2 = [(50.848677, 4.338074), (50.833264, 4.344961), (50.840809, 4.366227), (50.852455, 
4.367945 ), (50.858306, 4.346693)]
poly_2 = Polygon(coords2)
p2 = Point(50.811948, 4.382617)
print(p2.within(poly_2))
p2__ = nearest_points(poly_2, p2)
print("****:",p2__[0])

and the result is: ****: POINT (50.840809 4.366227) which is the nearest point from the geometry. I would like to get the real nearest point

any idea?

That is easy now, you know that the resulting point is going to lie on the line segment connecting 2 points on the polygon, and that one of these points is the closest point that you are looking for. This should be easy as you can just calculate the midpoint between the two points and if your original result point lies on either side of the mid point the point is closer to that particular point. eg: if the point lies on the first half of line segment AB then the closest point will be A, however, if it lies on the second part, then it is closer to point B.

Now the only remaining task is to find the Line segment AB that goes through the resulting point from your computation. For this simply iterate over each edge of polygon, get eq of line in terms of y=mx+c and compute if your answer satisfies the eq of line.

Hope this helps!

the nearest_points algorithm works as you would like it to, it returns the point anywhere on the shape which is closest to the other shape. It's just that in your case, the corner point of the polygon happens to actually be the closest point. Here is an illustration: 在此处输入图像描述

The point p2 which you have given is the blue point in the upper left corner. As the blue circle shows, the corner of your polygon in red happens to be the nearest point to p2 . If we assume a new hypothetical point p3 with the coordinates (50.82, 4.36) (in orange on the plot), the nearest_points algorithm returns a point on the polygon, not a corner point (~ (50.837, 4.354) in this case).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM