Skip to content

Instantly share code, notes, and snippets.

@philshem
Last active August 29, 2015 14:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save philshem/564ef37a96b3f4dd575c to your computer and use it in GitHub Desktop.
Save philshem/564ef37a96b3f4dd575c to your computer and use it in GitHub Desktop.
Google reverse geocoding for a list of latitude & longitude (CSV output)
import requests
urlbase = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='
key = None
# list of latitude, longitude pairs
latlong = [(40.714224,-73.961452), (47.3667, 8.5500)]
for xy in latlong:
url = urlbase + str(xy[0])+','+str(xy[1])
if key is not None:
url += '&key='+str(key)
# make request to google
r = requests.get(url)
# parse data
data = r.json()
# get desired country fields
short_name = data.get('results')[-1].get('address_components')[0].get('short_name')
long_name = data.get('results')[-1].get('address_components')[0].get('long_name')
# print csv output
print ','.join((str(xy[0]),str(xy[1]), short_name, long_name))
@philshem
Copy link
Author

Output looks like this:
40.714224,-73.961452,US,United States
47.3667,8.55,CH,Switzerland

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment