Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
MapQuest bulk geocoder
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
You can’t perform that action at this time.