我正在尝试使用网上找到的这个函数来计算地球上两个纬度和经度点之间的距离。
但是,我不知道如何传递纬度和经度值,因为我替换了 lat1
、lon1
和 lat2
、lon2
,我每次都会收到错误。
我在哪里输入我想要的纬度和经度值?
import math
def distance(origin, destination):
lat1, lon1 = origin
lat2, lon2 = destination
radius = 6371 # km
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
编辑: 例如,如果我有
lat1 = 20 and lon1 = 100
lat2 = 30 and lon2 = 110
为什么我用函数中的数字替换lon1时会失败?
最佳答案
像这样使用它:
distance((lat1, lon1), (lat2, lon2))
请注意,该函数接收两个二元素元组(或两个二元素列表,它们是相同的)作为参数,每个元组代表一个(纬度,经度)对。等价:
origin = (lat1, lon1)
destination = (lat2, lon2)
distance(origin, destination)
关于python - 如何将参数传递给 Python 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16826841/