如何从多边形中找到垂直距离?

3

我有n个坐标点,从这些点创建了一个多边形,现在如果一个坐标点在这个多边形中,我该如何找到它距离多边形的垂直距离?

coords = [(45.888106581826065, 8.512891340789281), (45.89087605100282, 8.51131888355673), (45.89242907135495, 8.51043574866833), (45.88810733356788, 8.512894063368899), (45.890876868519385, 8.51132182341189), (45.892063379278696, 8.510647148893547), (45.89243094789967, 8.510442653438174), (45.88811958097381, 8.512938419782168), (45.89088904461223, 8.51136560966078), (45.89207575921023, 8.510692030810025), (45.89244290698806, 8.51048665710127), (45.88813186579548, 8.512982911786311), (45.89090145183551, 8.511410227156235), (45.89245416375836, 8.510528076647585), (45.88813271861146, 8.512986000437545), (45.89090242476677, 8.511413725908412), (45.89245495631277, 8.510530992872562)]

需要检查是否在多边形内部的点:

p2 = Point(45.88831, 8.51283)

检查坐标点(p2)是否在多边形内:

poly = MultiPoint(coords).convex_hull
    if p2.within(poly):
        print("Givien point is in polygon")

我尝试使用 boundary.distance 函数来计算距离,结果得到的是4.7144012366024,但不确定这是否是垂直距离或其他什么距离!

print(poly.boundary.distance(p2))
#output: 4.71440123660249

有人能帮我获取离该点垂直的距离吗?


1
你想要最短的距离还是所有的距离?如果垂线落在边界外怎么办?你的问题没有明确说明。 - user1196549
@YvesDaoust 对不起,如果我的问题没有表述清楚。如问题中所示,我想找到点到左右线的距离,仅当该点位于多边形内时。 - L Lawliet
抱歉,这并没有真正澄清问题。是多边形还是只有两条线?如果垂线的底部在边界外面怎么办?需要先进行点在多边形内的测试吗? - user1196549
1个回答

1
对于每条多边形边缘AB,使用向量的点积进行点CAB上的投影,并得到其长度:
t = (AB.dot.AC) / (AB.dot.AB)  ## ratio of  AP / AB
L = length(t*AB - AC)  ## CP distance at the picture

请注意,对于超出 0..1 范围的 t 参数,投影位于 AB 的延长线上。

enter image description here

例子:

import math
def proj(x1,y1,x2,y2,cx,cy):
    dx = x2 - x1
    dy = y2 - y1
    cdx = cx - x1
    cdy = cy - y1
    t = (cdx * dx + cdy * dy) / (dx * dx + dy * dy)
    if t < 0 or t > 1:
        print("Projection lies outside segment")
    px = x1 + t * dx
    py = y1 + t * dy
    print("Projection coordinates: %5.1f %5.1f" % (px, py))
    nlen = math.hypot(t * dx - cdx, t * dy - cdy)
    print("Distance from point to line: %5.1f" % nlen)
    alonglen = math.hypot(t * dx, t * dy)
    print("Along segment distance:  %5.1f" % alonglen)

proj(0, 0, 4, 16/3, 0, 5)

>>
Projection coordinates:   2.4   3.2
Distance from point to line:   3.0
Along segment distance:    4.0

可能是一个简单的问题,但能告诉我如何计算cxcy吗? - L Lawliet
在Python语言中 - L Lawliet
cx和cy是您要测试的点(在您的问题中为p2)的坐标。 - MBo
明白,谢谢。 - L Lawliet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接