Last active
November 16, 2016 21:10
-
-
Save dannguyen/682f8c42c9f100405e04 to your computer and use it in GitHub Desktop.
more generic version of mapzen-geocoder in python, used to get city locations in the U.S. https://mapzen.com/documentation/search/
This file contains hidden or 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
from csv import DictReader, DictWriter | |
from os import environ | |
from time import sleep | |
import requests | |
FNAME = 'mx-syria.csv' | |
ONAME = FNAME + 'geocoded.csv' | |
API_KEY = environ['MAPZEN_SEARCH_KEY'] | |
BASE_URL = 'https://search.mapzen.com/v1/search' | |
def foo_geocode(address_text, country = 'USA'): | |
resp = requests.get(BASE_URL, | |
params = {'api_key': API_KEY, 'size': 1, | |
'text': address_text, 'boundary.country': country}) | |
data = resp.json() | |
bbox = data['bbox'] | |
pt = {} | |
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, U.S." % (row['City'], row['Destination State']) | |
try: | |
pt = foo_geocode(addr) | |
except Exception as err: | |
print(addr) | |
print("\tError:", err) | |
else: | |
print(addr, 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