Created
September 10, 2013 15:31
-
-
Save themiurgo/6511149 to your computer and use it in GitHub Desktop.
MapQuest bulk geocoder
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
import requests | |
API_KEY = "" # FILL THIS | |
class Geocoder(object): | |
endpoint = "http://www.mapquestapi.com/geocoding/v1/batch" | |
endpoint = "http://open.mapquestapi.com/geocoding/v1/batch" | |
def __init__(self, api_key): | |
self.api_key = api_key | |
def geocode_bunch(self, locations): | |
data = { | |
'location': locations, | |
'key': self.api_key, | |
} | |
response = requests.get(self.endpoint, params=data) | |
response = response.json() | |
# Repack response as {'text': [result1, result2, ...], ...} | |
results = response['results'] | |
output = {} | |
for result in results: | |
key = result['providedLocation']['location'] | |
value = result['locations'] | |
output[key] = value | |
return output | |
class CityGeocoder(Geocoder): | |
def geocode_bunch(self, locations): | |
results = super(CityGeocoder, self).geocode_bunch(locations) | |
output = {} | |
for query, locations in results.iteritems(): | |
first_city = None | |
for location in locations: | |
if location['geocodeQuality'] == "CITY": | |
location_string = location['adminArea5'] | |
location_string = ', '.join([location['adminArea5'], | |
location['adminArea4'], location['adminArea3'], | |
location['adminArea1']]) | |
first_city = location_string | |
break | |
output[query] = first_city | |
return output | |
if __name__ == "__main__": | |
locations = ["Acate", "Ragusa", "Birmingham"] | |
#geocoder = Geocoder(API_KEY) | |
#out = geocoder.geocode_bunch(locations) | |
geocoder = CityGeocoder(API_KEY) | |
outcity = geocoder.geocode_bunch(locations) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment