python - 通过 Google Cloud Maps Directions API 获取距离

标签 python google-maps google-directions-api

我正在尝试获取公交车站之间的距离,以粗略估计公交车何时来。我知道有一些应用程序和服务可以执行此操作,但我想自己执行此操作。

我得到了结果对象,但不知道如何获取距离。 Debug shows directions_result is a list with length of 0 (zero)

(代码来自GC Maps Directions API Python Client documentation。)

import googlemaps
from datetime import datetime
# GC Maps Directions API
coords_0 = '43.70721,-79.3955999'
coords_1 = '43.7077599,-79.39294'
gmaps = googlemaps.Client(key=api_key)
# Request directions via public transit
now = datetime.now()
directions_result = gmaps.directions(coords_0, coords_1, mode="driving", departure_time=now, avoid='tolls')
distance = directions_result.<what_im_trying_to_figure_out>

提前致谢。

最佳答案

我已经运行了你的代码,directions_result 对我来说长度为 1。要获取总距离,请尝试以下代码:

# Import libraries
import googlemaps
from datetime import datetime
# Set coords
coords_0 = '43.70721,-79.3955999'
coords_1 = '43.7077599,-79.39294'
# Init client
gmaps = googlemaps.Client(key="KEY")
# Request directions
now = datetime.now()
directions_result = gmaps.directions(coords_0, coords_1, mode="driving", departure_time=now, avoid='tolls')

# Get distance
distance = 0
legs = directions_result[0].get("legs")
for leg in legs:
    distance = distance + leg.get("distance").get("value")
print(distance) # 222 i.e. 0.2 km

希望这对您有帮助!

关于python - 通过 Google Cloud Maps Directions API 获取距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58053077/

相关文章:

python - 正则表达式表情符号Unicode

python - 如何使用 pydoc 仅查看文档文本

python - Swagger-codegen - 如何自定义客户端 SDK 调用名称?

Python:来自导入错误

google-maps - 融合表空间查询

javascript - 是否可以在客户端上显示没有 LatLong 的 Google map 圆圈

javascript - 将谷歌地图保存为图像 - 使用javascript(能够截屏)

ios - 如何向 google Direction api 发送请求以快速获取路径

android - 从 Android 调用 Google 方向 API 时返回 REQUEST_DENIED

android - 谷歌路线 API : Get the current step JSON-Object to current position on Android