如何计算两个位置之间的距离

时间:2013-06-03 22:19:16

标签: python

我使用http://maps.googleapis.com/maps/api/geocode/json获取lat和long 并保存到DB中。 我正在尝试编写在两个位置之间计算的代码。 是否有任何好的api计算两个距离之间的距离。 我在亚洲和欧洲有一些地方。 谷歌距离只返回我想要实际距离的行驶距离。 提前谢谢。

1 个答案:

答案 0 :(得分:2)

您可以使用Haversine公式计算距离

此处,origindestination是lat,long tuples

import math

def haversine(origin, destination):

    lat1, lon1 = origin
    lat2, lon2 = destination
    radius = 6371

    dlat = math.radians(lat2-lat1)
    dlon = math.radians(lon2-lon1)
    a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) \
        * math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2)
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
    d = radius * c

    return d

c1 = [43.47066971,-80.54305153]
c2 = [43.46745,-80.54319]

print haversine(c1, c2) # 0.358189763734