Skip to content

Instantly share code, notes, and snippets.

@tbuckl
Last active August 29, 2015 14:17
Show Gist options
  • Save tbuckl/0ecfbbb546913c7d9814 to your computer and use it in GitHub Desktop.
Save tbuckl/0ecfbbb546913c7d9814 to your computer and use it in GitHub Desktop.
google_maps_directions_api
import googlemaps
import os
import csv
import pandas
from array import array
import numpy as np
gmaps = googlemaps.Client(key=os.environ['GMAPSKEY'])
df_s = pandas.io.parsers.read_csv('tripdata.csv',sep=',')
df_s['distance'] = np.nan
df_s['duration'] = np.nan
df = df_s[1600:3900]
mtc_modes = df['mode'].unique()
google_modes = ["driving","driving","driving","walking","bicycling","driving","driving"]
mode_map = dict(zip(mtc_modes.tolist(),google_modes))
######THESE MODES ARE NOT MAPPING RIGHT
print("Modes are not Mapping right--check unique(array) in lines above")
def composeRequest(orig_y,orig_x,dest_y,dest_x,mode):
origin = str(orig_y) + "," + str(orig_x)
destination = str(dest_y) + "," + str(dest_x)
mode = mode_map[mode]
r = {'origin':origin,'destination':destination,'mode':mode}
return r
results = []
def parse_directions_result(directions_result):
duration = directions_result[0]['legs'][0]['duration']['value']
distance = directions_result[0]['legs'][0]['distance']['value']
return {'duration':duration,'distance':distance}
for index, row in df.iterrows():
r = composeRequest(row['orig_y'], row['orig_x'], row['dest_y'], row['dest_x'], row['mode'])
directions_result = gmaps.directions(r['origin'],
r['destination'],
r['mode'])
try:
a_result = parse_directions_result(directions_result)
except:
a_result = {'duration':-99999,'distance':-99999}
df.loc[index,'duration'] = a_result['duration']
df.loc[index,'distance'] = a_result['distance']
df.to_csv('tripdata_google1600_3750.csv')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment