Skip to content

Instantly share code, notes, and snippets.

@dannguyen
Created December 1, 2015 20:35
Show Gist options
  • Select an option

  • Save dannguyen/31f747419caba40f83e4 to your computer and use it in GitHub Desktop.

Select an option

Save dannguyen/31f747419caba40f83e4 to your computer and use it in GitHub Desktop.
Geocoding Oklahoma schools with Mapzen
from csv import DictReader, DictWriter
from os import environ
from time import sleep
import requests
# http://www.ok.gov/sde/state-school-directory
FNAME = 'ok_directory_2015.csv'
ONAME = 'ok_directory_2015--geocoded.csv'
API_KEY = environ['MAPZEN_SEARCH_KEY']
BASE_URL = 'https://search.mapzen.com/v1/search'
OK_LAT = 35.470
OK_LNG = -97.500
# Using the priority boundary feature in Mapzen Search
# https://mapzen.com/documentation/search/search/#prioritize-within-a-circular-region
def foo_ny_geocode(address_text,
focus_point = {'lat': OK_LAT ,'lon': OK_LNG}):
resp = requests.get(BASE_URL,
params = {'api_key': API_KEY, 'size': 1,
'text': address_text,
'focus.point.lat': focus_point['lat'],
'focus.point.lon': focus_point['lon'],
'boundary.circle.lat': focus_point['lat'],
'boundary.circle.lon': focus_point['lon'],
'boundary.circle.radius': 400})
data = resp.json()
bbox = data['bbox']
pt = {'distance_from_focus': data['features'][0]['properties']['distance']}
pt['lat'] = (bbox[1] + bbox[3]) / 2
pt['lon'] = (bbox[0] + bbox[2]) / 2
return pt
r = open(FNAME)
rcsv = DictReader(r)
w = open(ONAME, 'w')
wcsv = DictWriter(w, fieldnames = rcsv.fieldnames + ['latitude', 'longitude'])
wcsv.writeheader()
for row in rcsv:
addr = "%s %s, Oklahoma, %s" % (
row['Mailing Address'], row['City'], row['Zip'])
if 'PO BOX' not in addr.upper():
try:
pt = foo_ny_geocode(addr)
except Exception as err:
print(addr)
print("\t", err)
else:
print(addr, pt['distance_from_focus'], pt['lat'], pt['lon'])
row['latitude'] = pt['lat']
row['longitude'] = pt['lon']
wcsv.writerow(row)
sleep(0.2)
w.close()
r.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment