Skip to content

Instantly share code, notes, and snippets.

@gsf
Created March 13, 2019 02:42
Show Gist options
  • Save gsf/be8ea7898d89d9c50f097e6ce0324f89 to your computer and use it in GitHub Desktop.
Save gsf/be8ea7898d89d9c50f097e6ce0324f89 to your computer and use it in GitHub Desktop.
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