Last active
March 14, 2019 23:24
-
-
Save chizou/28ebc01748f178a6e80cbf9b7ff9ce0b to your computer and use it in GitHub Desktop.
brewery-geocoder
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
#!/usr/bin/python3 | |
""" | |
Use Google Map's Geocoding service to geocode addresses of breweries using the csv | |
format available from https://www.bcca.com/pflist/. This could technically be used | |
to geocode any csv list of addreses that has the following columns: | |
Name or Address, City, State, Zip | |
""" | |
from datetime import datetime | |
import csv | |
import googlemaps | |
import pprint | |
with open('/home/achou/googlemapkey', 'r') as myfile: | |
google_api_key = myfile.read().replace('\n', '') | |
myfile.close() | |
gmaps = googlemaps.Client(key=google_api_key) | |
with open('brewery_list.csv', 'r', encoding='utf-8-sig') as in_file, open('geolocated_brewery_list.csv', 'a+') as out_file: | |
csv_reader = csv.DictReader(in_file) | |
out_header = csv_reader.fieldnames + ['Lat'] + ['Lon'] | |
csv_writer = csv.DictWriter(out_file, out_header) | |
csv_writer.writeheader() | |
line_count = 1 | |
for row in csv_reader: | |
# Some entries don't have addresses so use Google to find the address by business name | |
if row['Address']: | |
address = f"{row['Address']}, {row['City']}, {row['State']}, {row['Zip']}" | |
else: | |
address = f"{row['Name']}, {row['City']}, {row['State']}, {row['Zip']}" | |
try: | |
geocode_result = gmaps.geocode(address) | |
except Error as e: | |
print("Failed geocode: " + address) | |
continue | |
try: | |
# If Google found us an address, let's save it | |
if not row['Address']: | |
row['Address'] = geocode_result[0]['formatted_address'].split(',')[0] | |
row['Lat'] = geocode_result[0]['geometry']['location']['lat'] | |
row['Lon'] = geocode_result[0]['geometry']['location']['lng'] | |
except IndexError: | |
print("Failed lat/lon: " + address) | |
else: | |
csv_writer.writerow(row) | |
line_count += 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment