Skip to content

Instantly share code, notes, and snippets.

@akshayhs
Created October 13, 2021 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akshayhs/70f1beacc0baf67823bcba68c48811ec to your computer and use it in GitHub Desktop.
Save akshayhs/70f1beacc0baf67823bcba68c48811ec to your computer and use it in GitHub Desktop.
Django and Google maps: Extracting the coordinates for a given location in string using Geocoding API
# Please read carefully
# The code below relies on Google Maps API services, precisely the Geocoding API.
# In order to play with the code below, you will need a Google Maps API key with all the above API enabled in your Google Cloud API dashboard
from django.conf import settings
from pprint import pprint
# Assuming googlemaps python module has been installed
from googlemaps import Client
# Initialize the client
gmaps = Client(key=settings.YOUR_GOOGLE_MAPS_API_KEY_HERE)
# Geocoding a particular location where the argument is a string
location = gmaps.geocode('Bengaluru') # For example, other complete addresses such as "1600 Pennsylvania Avenue, N.W." works as well
pprint(location)
# Resulting output
[{'address_components': [{'long_name': 'Bengaluru',
'short_name': 'Bengaluru',
'types': ['locality', 'political']},
{'long_name': 'Bangalore Urban',
'short_name': 'Bangalore Urban',
'types': ['administrative_area_level_2',
'political']},
{'long_name': 'Karnataka',
'short_name': 'KA',
'types': ['administrative_area_level_1',
'political']},
{'long_name': 'India',
'short_name': 'IN',
'types': ['country', 'political']}],
'formatted_address': 'Bengaluru, Karnataka, India',
'geometry': {'bounds': {'northeast': {'lat': 13.173706, 'lng': 77.8826809},
'southwest': {'lat': 12.7342888, 'lng': 77.3791981}},
'location': {'lat': 12.9715987, 'lng': 77.5945627},
'location_type': 'APPROXIMATE',
'viewport': {'northeast': {'lat': 13.173706, 'lng': 77.8826809},
'southwest': {'lat': 12.7342888,
'lng': 77.3791981}}},
'place_id': 'ChIJbU60yXAWrjsR4E9-UejD3_g',
'types': ['locality', 'political']}]
# Extracting the coordinate data from the above result
coords = location[0]['geometry']['location']
print(coords['lat']) # 12.9715987
print(coords['lng']) # 77.5945627
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment