Created
March 13, 2019 02:42
-
-
Save gsf/be8ea7898d89d9c50f097e6ce0324f89 to your computer and use it in GitHub Desktop.
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
import csv | |
import googlemaps | |
import os | |
import re | |
import time | |
gmaps = googlemaps.Client(key=os.getenv('GOOGLE_API_KEY')) | |
origins = ['559 Carpenter Ln, Philadelphia, PA 19119, USA'] | |
destinations = [] | |
rows = [] | |
def write_rows_with_dist(write_head): | |
matrix = gmaps.distance_matrix(origins, destinations, units='imperial') | |
print(matrix) | |
with open('pvpd7.csv', 'a') as newfile: | |
fieldnames = ['VendorNo', 'VendorName', 'AddressLine1', 'AddressLine2', | |
'City', 'State', 'ZipCode', 'TelephoneNo', 'Sort', 'Column1', | |
'Purchases', 'GoogleAddress', 'Distance'] | |
writer=csv.DictWriter(newfile, fieldnames) | |
if write_head: | |
writer.writeheader() | |
for row in rows: | |
if 'destination_index' in row: | |
row['GoogleAddress'] = matrix['destination_addresses'][row['destination_index']] | |
if matrix['rows'][0]['elements'][row['destination_index']]['status'] == 'OK': | |
row['Distance'] = matrix['rows'][0]['elements'][row['destination_index']]['distance']['text'] | |
del row['destination_index'] | |
writer.writerow(row) | |
with open('pvpd6.csv', newline='') as csvfile: | |
reader = csv.DictReader(csvfile) | |
count = 0 | |
first_write = True | |
for row in reader: | |
if not row['GoogleAddress']: | |
destination = row['VendorName'] | |
if not re.sub('[\W]+', '', row['AddressLine1']).lower().startswith('pobox'): | |
destination = destination + ", " + row['AddressLine1'] | |
destinations.append(destination) | |
row['destination_index'] = len(destinations) - 1 | |
count += 1 | |
rows.append(row) | |
if count > 0 and count % 25 == 0: | |
write_rows_with_dist(first_write) | |
first_write = False | |
rows = [] | |
destinations = [] | |
time.sleep(2) | |
write_rows_with_dist(first_write) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment