Last active
December 17, 2015 08:38
-
-
Save douglas-c-thomas/5581233 to your computer and use it in GitHub Desktop.
Reverse Geocoding (lat, long -> {city, state, zip_code})
This file contains 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
def reverse_geocode_location(lat, long): | |
""" | |
For a given geolocation, return the city, state and zip code in a dictionary | |
""" | |
try: | |
location = {} | |
lat_long = '%s,%s' % (lat, long) | |
if lat not in ('', None) and long not in ('', None): | |
response = urllib2.urlopen("https://maps.googleapis.com/maps/api/geocode/json?%s" % | |
urllib.urlencode({'latlng': lat_long, 'sensor':'false'})) | |
data = response.read() | |
results = json.loads(data).get('results') | |
if results is not None and len(results) > 0: | |
for result in results: | |
if 'postal_code' in result['types'][0]: | |
address_components = result.get('address_components', {}) | |
for address_component in address_components: | |
if 'locality' in address_component.get('types', []): | |
location['city'] = address_component.get('long_name') | |
if 'administrative_area_level_1' in address_component.get('types', []): | |
location['state'] = address_component.get('short_name') | |
if 'postal_code' in address_component.get('types', []): | |
location['zip_code'] = address_component.get('short_name') | |
return location | |
except: | |
logger.info("problem reverse geocoding location") | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment