Last active
August 16, 2021 22:28
-
-
Save nickbalch/5901e46d0170ff3d4de498a246283ed1 to your computer and use it in GitHub Desktop.
Google API directions extractor. I have a need to export Google turn directions into a structured format so that they can be presented as printouts. Google Python reference is here: https://googlemaps.github.io/google-maps-services-python/docs/. Google's github for the python lib - https://github.com/googlemaps/google-maps-services-python which …
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://stackoverflow.com/questions/13206695/json-parsing-of-google-maps-direction-api-in-python | |
import re | |
import csv | |
from googlemaps import Client | |
mapService = Client(key='') | |
directions = mapService.directions('start','end',waypoints'one|two|three') | |
directions = directions[0] | |
i=1 | |
f = open('directions4.csv', 'w') | |
writer = csv.writer(f,delimiter='+') | |
for leg in directions['legs']: | |
startAddress = leg['start_address'] | |
print "======================================================================" | |
print "Start Address:", startAddress | |
endAddress = leg['end_address'] | |
print "End Address", endAddress | |
writer.writerow(['']) | |
writer.writerow([startAddress+' to '+endAddress]) | |
for step in leg['steps']: | |
html_instructions = step['html_instructions'] | |
# simple regex to remove html tags plus need to sort out encoding | |
instructions=re.sub('<[^<]+?>', '',html_instructions ).encode('utf-8') | |
# distance = step['distance']['text'] | |
# for distance and time, we only want the numbers, not the units or other text: | |
meters = step['distance']['value'] | |
distance= '{:.4f}'.format(meters/float(1609)) | |
# couldn't work out the time unit used in the api, but its ok to take the string and split it: | |
time = step['duration']['text'].split(' ',1)[0] | |
# not all directions have a maneuver command, but they are useful: | |
maneuver = '' | |
if step.has_key('maneuver'): | |
maneuver = step['maneuver'].replace('turn-','').upper() | |
print "STEP {} {} {} {} {}".format(i, maneuver, instructions, distance, time) | |
writer.writerow([i,maneuver, instructions, distance, time]) | |
i = i+1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment