[英]Using distance matrix to calculate distance between points with latitude and longitude in Python
I am trying to calculate the distances between points by using gmaps.distance_matrix() with a google api.我试图通过使用 gmaps.distance_matrix() 和 google api 来计算点之间的距离。 The code outputs unreasonable results, but I can't find where the error is.
代码输出不合理的结果,但我找不到错误在哪里。
Here is my code:这是我的代码:
gmaps = googlemaps.Client(key=API_key)
origins = ['41.844775, -87.626719', '41.614779, -87.55133599999999', '41.567222, -87.550503', '41.800635, -87.604568', '41.69154, -87.62171', '41.894244, -87.62284100000001', '42.010228000000005, -72.840536', '42.010228000000005, -72.840536', '42.010228000000005, -72.840536', '42.010228000000005, -72.840536', '47.617177000000005, -122.208579']
destinations = ['41.614779, -87.55133599999999', '41.567222, -87.550503', '41.800635, -87.604568', '41.69154, -87.62171', '41.894244, -87.62284100000001', '42.010228000000005, -72.840536', '42.010228000000005, -72.840536', '42.010228000000005, -72.840536', '42.010228000000005, -72.840536', '47.617177000000005, -122.208579', '41.894244, -87.62284100000001']
actual_distance_testing = []
for origin, destination in zip(origins, destinations):
result = gmaps.distance_matrix(origin, destinations, mode='driving')["rows"][0]["elements"][0]["distance"]["value"]
result = result/1000
actual_distance_testing.append(result)
print(actual_distance_testing)
This is the output I got from the code above:这是我从上面的代码得到的输出:
[31.716, 0.0, 7.257, 28.524, 13.981, 39.688, 1416.856, 1416.856, 1416.856, 1416.856, 3347.006]
The first value is correct, but the rest of them are not accurate.第一个值是正确的,但其余的都不准确。 This is my expected and correct result:
这是我预期的正确结果:
[31.716, 7.247, 33.71, 14.976, 25.557, .....]
For more information: I am calculating the distance in km.有关更多信息:我正在计算以公里为单位的距离。 For example, the distance between '41.844775, -87.626719' and '41.614779, -87.55133599999999' is 31.716 km.
例如,'41.844775, -87.626719' 和 '41.614779, -87.55133599999999' 之间的距离为 31.716 公里。
I tried to calculate the second value only, and the output is correct if I do the calculation separately as followed:我试图只计算第二个值,如果我单独进行计算,输出是正确的,如下所示:
o = (41.614779, -87.55133599999999); d = (41.567222, -87.550503)
result = gmaps.distance_matrix(o, d, mode='driving')["rows"][0]["elements"][0]["distance"]["value"]/1000
print(result)
7.247
here I think you should look at the full response to understand how Google API provides the requested query.在这里,我认为您应该查看完整的响应以了解 Google API 如何提供请求的查询。 I recommend for you to trace the response first.
我建议您首先跟踪响应。
result['rows'][0]['elements']= [{'distance': {'text': '31.7 km', 'value': 31715}, 'duration': {'text': '26 mins', 'value': 1568}, 'status': 'OK'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.