如何找到与多边形的垂直距离?

问题描述

如果该多边形中有坐标,我现在有 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

谁能帮我得到点的垂直距离?

解决方法

对于每个多边形边 AB 使用向量的点积将点 C 投影到 AB 上并得到它的长度:

t = (AB.dot.AC) / (AB.dot.AB)  ## ratio of  AP / AB
L = length(t*AB - AC)  ## CP distance at the picture

请注意,对于 t 范围外的 0..1 参数,投影取决于 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,4,16/3,5)

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