2

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.

fbraga
  • 711
  • 4
  • 9
Ken Shibata
  • 71
  • 1
  • 9
  • BTW, I removed the `# Geocoding an address` part from the sample code. – Ken Shibata Sep 22 '19 at 20:19
  • If you are looking for the math behind this and you can read JavaScript, maybe this article will help you: http://www.movable-type.co.uk/scripts/latlong.html – John Hanley Sep 22 '19 at 20:45
  • @John Hanley I'm not looking for the math, but the way to get the distance through the Python Client. Also, I want the driving distance, not the straight distance. – Ken Shibata Sep 22 '19 at 20:48
  • Sorry, I interpreted your question as trying to duplicate what the `gmaps.directions` API does. Your example is not complete, therefore I don't know why the results are an empty array. Edit your question and include real code. Read this to understand how to post a question involve programming. https://stackoverflow.com/help/minimal-reproducible-example – John Hanley Sep 22 '19 at 22:21
  • Post edited. Added import statementts and real coordnates tested on Google Maps (webapp). – Ken Shibata Sep 24 '19 at 01:28

1 Answers1

4

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!

Ken Shibata
  • 71
  • 1
  • 9
evan
  • 5,443
  • 2
  • 11
  • 20