Last active
January 3, 2016 00:19
-
-
Save jbradach/8381802 to your computer and use it in GitHub Desktop.
Uses the Google Distance Matrix API to calculate driving times between the origin and destination values in a given file.Google requires that all use of this API be related to the display of information on a Google Map.
This file contains hidden or 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
from sys import argv | |
import requests | |
import csv | |
from time import sleep | |
# https://gist.github.com/jbradach/8381802 | |
def main(): | |
script, filein, fileout = argv | |
baseurl = 'https://maps.googleapis.com/maps/api/distancematrix/json?' | |
reader = csv.reader(open(filein, 'r'), dialect='excel-tab') | |
next(reader, None) | |
datain = [] | |
for row in reader: | |
datain.append(row) | |
writer = csv.writer(open(fileout, 'w'), dialect='excel-tab') | |
headers = ['fileid', 'origin', 'destination', 'status', | |
'distance_value','distance_text', | |
'duration_value', 'duration_text'] | |
writer.writerow(headers) | |
i = 1 | |
for row in datain: | |
rout = [] | |
r = requests.get(baseurl + 'origins=' + row[1] + | |
'&destinations=' + row[2] + '&sensor=false&units=imperial') | |
r = r.json() | |
rout.append(row[0]) | |
status = r['rows'][0]['elements'][0]['status'] | |
if status == 'ZERO_RESULTS': | |
rout.append(r['origin_addresses'][0]) | |
rout.append(r['destination_addresses'][0]) | |
rout.append(status) | |
elif status == 'OK': | |
rout.append(r['origin_addresses'][0]) | |
rout.append(r['destination_addresses'][0]) | |
rout.append(status) | |
rout.append(r['rows'][0]['elements'][0]['distance']['value']) | |
rout.append(r['rows'][0]['elements'][0]['distance']['text']) | |
rout.append(r['rows'][0]['elements'][0]['duration']['value']) | |
rout.append(r['rows'][0]['elements'][0]['duration']['text']) | |
else: | |
print 'Error:' + status | |
writer.writerow(rout) | |
if i % 50 == 0: | |
sleep(10) | |
i =+ 1 | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment