Skip to content

Instantly share code, notes, and snippets.

@douglas-c-thomas
Last active December 17, 2015 08:38
Show Gist options
  • Save douglas-c-thomas/5581233 to your computer and use it in GitHub Desktop.
Save douglas-c-thomas/5581233 to your computer and use it in GitHub Desktop.
Reverse Geocoding (lat, long -> {city, state, zip_code})
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