Ken Shibata
Ken Shibata

Reputation: 91

Get distance from Google Cloud Maps Directions API

I'm trying to get the distance between bus stops to get a rough estimate of when the bus is coming. I know there are apps and services that do this, but I want to do it myself.

I got the result object, but don't know how to get the distance. Debug shows directions_result is a list with length of 0 (zero)

(The code is from the 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>

Thanks in advance.

Upvotes: 2

Views: 2705

Answers (1)

evan
evan

Reputation: 5699

I've ran your code and directions_result has length 1 for me. To get the total distance please try the code below:

# 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

Hope this helps you!

Upvotes: 4

Related Questions