Skip to content

Instantly share code, notes, and snippets.

@derekeder
Created May 21, 2025 00:56
Show Gist options
  • Save derekeder/17da34f39833b0e98b5436bfc5a9d9ec to your computer and use it in GitHub Desktop.
Save derekeder/17da34f39833b0e98b5436bfc5a9d9ec to your computer and use it in GitHub Desktop.
import requests
from csv import DictReader, DictWriter
from tqdm import tqdm
def add_lat_long(input_file, output_file):
"Adds latitude and longitude to the primary table"
reader = DictReader(input_file)
fieldnames = []
for f in reader.fieldnames:
if "Column" not in f:
fieldnames.append(f)
fieldnames.extend(["Latitude", "Longitude", "Latitude_2", "Longitude_2"])
writer = DictWriter(output_file, fieldnames=fieldnames)
output_list = []
for row in tqdm(reader):
address = f"{row['Street Address']}, {row['City']} {row['State']} {row['Zip']}"
address = address.replace('\r', ' ').replace('\n', ' ')
results = geocode(address)
current = {}
for f in fieldnames:
current.update({
f: row.get(f)
})
current.update({
"Latitude": results[0]["geometry"]["location"]["lat"],
"Longitude": results[0]["geometry"]["location"]["lng"]
})
if len(results) > 1:
current.update({
"Latitude_2": results[1]["geometry"]["location"]["lat"],
"Longitude_2": results[1]["geometry"]["location"]["lng"]
})
output_list.append(current)
writer.writeheader()
writer.writerows(output_list)
def geocode(address):
"Feed addresses into google's geocoding service, and get list of results"
payload = {
"address": address,
"key": "GOOGLE_API_KEY"
}
response = requests.get(
"https://maps.googleapis.com/maps/api/geocode/json?",
params=payload
)
return response.json()['results']
with open('data/Primary_Info-Table_1.csv') as input:
with open ('data/formatted_primary.csv', 'w', newline='') as output:
add_lat_long(input, output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment