gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:22:42 24 4
gpt4 key购买 nike

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

我得到了结果对象,但不知道如何获取距离。 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com