简体   繁体   English

在 Shapely 或 GeoPandas 中查找多边形上最近点的坐标

[英]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.结果是: ****: POINT (50.840809 4.366227) 这是距离几何最近的点。 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.现在这很容易,您知道结果点将位于连接多边形上 2 个点的线段上,并且这些点之一是您正在寻找的最近点。 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.例如:如果该点位于线段 AB 的前半部分,那么最近的点将是 A,但是,如果它位于第二部分,则它更靠近 B 点。

Now the only remaining task is to find the Line segment AB that goes through the resulting point from your computation.现在剩下的唯一任务是找到穿过计算结果点的线段 AB。 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.为此,只需遍历多边形的每条边,根据 y=mx+c 获取线的 eq 并计算您的答案是否满足线的 eq。

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. nearest_points算法可以按照您的意愿工作,它返回形状上最接近另一个形状的任何位置的点。 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.您给出的点p2是左上角的蓝色点。 As the blue circle shows, the corner of your polygon in red happens to be the nearest point to p2 .如蓝色圆圈所示,红色多边形的角恰好是离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).如果我们假设一个新的假设点p3的坐标为(50.82, 4.36) (图中橙色),则nearest_points点算法返回多边形上的一个点,而不是角点(在这种情况下为 ~ (50.837, 4.354) )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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