根据纬度/经度获取两点之间的距离 [英] Getting distance between two points based on latitude/longitude

查看:106
本文介绍了根据纬度/经度获取两点之间的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试实现以下公式: http://andrew.hedges.name/experiments/haversine/ aplet可以很好地满足我测试的两点要求:

I tried implementing this formula: http://andrew.hedges.name/experiments/haversine/ The aplet does good for the two points I am testing:

但是我的代码无法正常工作.

Yet my code is not working.

from math import sin, cos, sqrt, atan2

R = 6373.0

lat1 = 52.2296756
lon1 = 21.0122287
lat2 = 52.406374
lon2 = 16.9251681

dlon = lon2 - lon1
dlat = lat2 - lat1
a = (sin(dlat/2))**2 + cos(lat1) * cos(lat2) * (sin(dlon/2))**2
c = 2 * atan2(sqrt(a), sqrt(1-a))
distance = R * c

print "Result", distance
print "Should be", 278.546

它返回的距离为 5447.05546147 .为什么?

The distance it returns is 5447.05546147. Why?

推荐答案

编辑:请注意,如果您只是需要一种快速简便的方法来查找两点之间的距离,我强烈建议建议使用下面的库尔特的答案中描述的方法,而不是重新实现Haversine -有关原理,请参阅他的帖子.

Just as a note, if you just need a quick and easy way of finding the distance between two points, I strongly recommend using the approach described in Kurt's answer below instead of re-implementing Haversine -- see his post for rationale.

此答案仅专注于回答OP遇到的特定错误.

This answer focuses just on answering the specific bug OP ran into.

这是因为在Python中,所有触发函数都使用弧度,而不是度数.

It's because in Python, all the trig functions use radians, not degrees.

您可以将数字手动转换为弧度,也可以使用 <数学模块中的c0> 函数:

You can either convert the numbers manually to radians, or use the radians function from the math module:

from math import sin, cos, sqrt, atan2, radians

# approximate radius of earth in km
R = 6373.0

lat1 = radians(52.2296756)
lon1 = radians(21.0122287)
lat2 = radians(52.406374)
lon2 = radians(16.9251681)

dlon = lon2 - lon1
dlat = lat2 - lat1

a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))

distance = R * c

print("Result:", distance)
print("Should be:", 278.546, "km")

距离现在返回正确的值278.545589351 km.

The distance is now returning the correct value of 278.545589351 km.

这篇关于根据纬度/经度获取两点之间的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆