GoogleMapsAddressesAPI - edorlando07/datasciencecoursera GitHub Wiki
import urllib2
import json
import itertools ##allows you to iterate between two lists within your loop.
##this is needed since we have 2 city lists that need to change
##see itertools.izip code below
##This section reads in the AddressMasterList.text file
##Creates one list for the Origin ['"Washington,DC"', '"Chicago,IL"']
##Creates one list for the Destination ['"Denver,CO"', '"Nashville,TN"']
recordList = []
originList = []
destinationList = []
employeeList = []
AddressFile = open('AddressMasterList00001to00400.txt','r')
for line in AddressFile:
rec, orig, dest, eeID = line.split()
recordList.append(rec)
originList.append(orig)
destinationList.append(dest)
employeeList.append(eeID)
AddressFile.close()
##This section loops through the various
##origins and destinations and inputs
##those origins and destinations into the
##url
for records,origins,destinations,employees in itertools.izip(recordList,originList,destinationList,employeeList):
city_urls = [
'https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins='\
+str(origins)\
+'&destinations='\
+str(destinations)\
+'&key=AIzaSyAxEGWmA1CAZgZsKSEba1FO_kKk420gNaI'
]
##loops through all urls
##must include the indentation since the loop above needs to occur first and then this one second.
##the loop above creates all the urls first, and then loops through the data within those urls
with open('AddressListOutput00001to00401.txt', 'a') as the_file:
##Prints the title headers
for url_ in city_urls:
f = urllib2.urlopen(url_)
json_string = f.read()
parsed_json = json.loads(json_string)
##need to research why you have to look within the list and then the dictionary or vice versa
minutes = (parsed_json['rows'][0]['elements'][0]['duration']['value'])/60
the_file.write(str(records) + '|' + str(origins) + '|' + str(destinations) + '|' + str(minutes)+'\n') #'\n' is needed to get the txt file to have multiple lines outputted
f.close()
the_file.close()```