【发布时间】:2011-05-05 10:00:31
【问题描述】:
当给定每一端点的纬度和经度时,我有一个短函数来计算一条线的中点。简单来说就是在经度大于-90度或者小于90度的情况下正常工作。对于地球的另一半,它提供了一个有点随机的结果。
该代码是http://www.movable-type.co.uk/scripts/latlong.html 提供的javascript 的python 转换,并且似乎符合here 和here 的更正版本。在比较两个 stackoverflow 版本时,我承认我不会用 C# 或 Java 编写代码,但我无法发现我的错误在哪里。
代码如下:
#!/usr/bin/python
import math
def midpoint(p1, p2):
lat1, lat2 = math.radians(p1[0]), math.radians(p2[0])
lon1, lon2 = math.radians(p1[1]), math.radians(p2[1])
dlon = lon2 - lon1
dx = math.cos(lat2) * math.cos(dlon)
dy = math.cos(lat2) * math.sin(dlon)
lat3 = math.atan2(math.sin(lat1) + math.sin(lat2), math.sqrt((math.cos(lat1) + dx) * (math.cos(lat1) + dx) + dy * dy))
lon3 = lon1 + math.atan2(dy, math.cos(lat1) + dx)
return(math.degrees(lat3), math.degrees(lon3))
p1 = (6.4, 45)
p2 = (7.3, 43.5)
print "Correct:", midpoint(p1, p2)
p1 = (95.5,41.4)
p2 = (96.3,41.8)
print "Wrong:", midpoint(p1, p2)
有什么建议吗?
【问题讨论】:
-
@S.Lott:utexas 代码有什么问题?
-
@S.Lott:短距离有什么相同的错误??
-
@John Machin:第二个示例提供的答案似乎不在两点之间。
-
@S.Lott:如果您的意思是 OP 的第二个示例 p1=(95.5,41.4) 等:纬度的 95.5 度是无效的——它将比北极更北。阅读我的答案- OP 得到了 lat 和 lon 颠倒并承认了。如果你的意思是别的,请解释一下。