Python 以经纬度计算点与线段之间的距离

Python 以经纬度计算点与线段之间的距离,python,latitude-longitude,Python,Latitude Longitude,我有一条定义了起点和终点的线段: A: x1 = 10.7196405787775 y1 = 59.9050401935882 B: x2 = 10.7109989561813 y2 = 59.9018650448204 其中x定义经度,y定义纬度 我也有一点: P: x0 = 10.6542116666667 y0 = 59.429105 如何计算线段与点之间的最短距离?我知道如何在笛卡尔坐标系下完成这项工作,但在长/纬度坐标系下不知道 下面是公式off的实现: def距离(p0、p

我有一条定义了起点和终点的线段:

A: 
x1 = 10.7196405787775
y1 = 59.9050401935882

B: 
x2 = 10.7109989561813
y2 = 59.9018650448204
其中x定义经度,y定义纬度

我也有一点:

P:
x0 = 10.6542116666667
y0 = 59.429105

如何计算线段与点之间的最短距离?我知道如何在笛卡尔坐标系下完成这项工作,但在长/纬度坐标系下不知道

下面是公式off的实现:

def距离(p0、p1、p2):#p3是点
x0,y0=p0
x1,y1=p1
x2,y2=p2
nom=abs((y2-y1)*x0-(x2-x1)*y0+x2*y1-y2*x1)
denom=((y2-y1)**2+(x2-x1)**2)**0.5
结果=nom/denom
返回结果
打印距离((0,0)、(3,4)、(5,6))
#应该测试不太明显的情况
断言1==距离((0,0)、(1,1)、(2,1))
#将0.001更改为测试所需的任何精度。
#请注意,它从来都不是完美的。。。
断言0.5*(2**0.5)-距离((0,0)、(1,0)、(0,1))<0.001

使用有用的Python地理编码库和大圆中点的公式,我们可以找到大圆弧与给定点之间的距离:

from math import sin, cos, atan2, sqrt, degrees, radians, pi
from geopy.distance import great_circle as distance
from geopy.point import Point


def midpoint(a, b):
    a_lat, a_lon = radians(a.latitude), radians(a.longitude)
    b_lat, b_lon = radians(b.latitude), radians(b.longitude)
    delta_lon = b_lon - a_lon
    B_x = cos(b_lat) * cos(delta_lon)
    B_y = cos(b_lat) * sin(delta_lon)
    mid_lat = atan2(
        sin(a_lat) + sin(b_lat),
        sqrt(((cos(a_lat) + B_x)**2 + B_y**2))
    )
    mid_lon = a_lon + atan2(B_y, cos(a_lat) + B_x)
    # Normalise
    mid_lon = (mid_lon + 3*pi) % (2*pi) - pi
    return Point(latitude=degrees(mid_lat), longitude=degrees(mid_lon))
在本例中给出:

# Example:
a = Point(latitude=59.9050401935882, longitude=10.7196405787775)
b = Point(latitude=59.9018650448204, longitude=10.7109989561813)
p = Point(latitude=59.429105, longitude=10.6542116666667)

d = distance(midpoint(a, b), p)
print d.km
# 52.8714586903

谷歌的HaveSeN:对于GIS类型的问题,你可以考虑张贴。然后在这里发布实际的编码问题。这可能是有趣的-@ReutSharabani,另一篇文章不仅涉及笛卡尔坐标,而不是球面坐标,而且非常相关的答案回答了不同的问题(到直线的距离,而不是到线段的距离)。这给出了到中点的距离。这与到线段的距离不同-例如,如果p接近a,d应该远小于a到b距离的一半。这对纬度/经度有效吗?我会担心隐含的度量空间假设。。。
# Example:
a = Point(latitude=59.9050401935882, longitude=10.7196405787775)
b = Point(latitude=59.9018650448204, longitude=10.7109989561813)
p = Point(latitude=59.429105, longitude=10.6542116666667)

d = distance(midpoint(a, b), p)
print d.km
# 52.8714586903