Skip to content

Instantly share code, notes, and snippets.

@pnavarrc
Last active September 20, 2023 12:43
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save pnavarrc/5379521 to your computer and use it in GitHub Desktop.
Save pnavarrc/5379521 to your computer and use it in GitHub Desktop.
Using Python requests and the Google Maps Geocoding API
# Using Python requests and the Google Maps Geocoding API.
#
# References:
#
# * http://docs.python-requests.org/en/latest/
# * https://developers.google.com/maps/
import requests
GOOGLE_MAPS_API_URL = 'http://maps.googleapis.com/maps/api/geocode/json'
params = {
'address': '221B Baker Street, London, United Kingdom',
'sensor': 'false',
'region': 'uk'
}
# Do the request and get the response data
req = requests.get(GOOGLE_MAPS_API_URL, params=params)
res = req.json()
# Use the first result
result = res['results'][0]
geodata = dict()
geodata['lat'] = result['geometry']['location']['lat']
geodata['lng'] = result['geometry']['location']['lng']
geodata['address'] = result['formatted_address']
print('{address}. (lat, lng) = ({lat}, {lng})'.format(**geodata))
# 221B Baker Street, London, Greater London NW1 6XE, UK. (lat, lng) = (51.5237038, -0.1585531)
@doi152
Copy link

doi152 commented Jan 24, 2023

After adding the key to params:

params = {
'address': '221B Baker Street, London, United Kingdom',
'sensor': 'false',
'region': 'uk',
'key' : 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
}

This is what i get from the terminal output:

Traceback (most recent call last):
File "c:/Users/Documents/google api key print.py", line 24, in
result = res['results'][0]
IndexError: list index out of range

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