How to get coordinates of address from Python


Question

I need to geocode an address to a latitude, longitude pair to display on Google Maps, but I need to do this server-side in Django. I could only find reference to the Javascript V3 API. How do I do it from Python?

1
12
4/27/2011 4:11:25 PM

Accepted Answer

I would suggest using Py-Googlemaps. To use it is easy:

from googlemaps import GoogleMaps
gmaps = GoogleMaps(API_KEY)
lat, lng = gmaps.address_to_latlng(address)

EDIT: If necessary, install Py-Googlemaps via: sudo easy_install googlemaps.

14
8/29/2019 1:03:09 PM

I would strongly recommend to use geopy. It will return the latitude and longitude, you can use it in the Google JS client afterwards.

>>> from geopy.geocoders import Nominatim
>>> geolocator = Nominatim()
>>> location = geolocator.geocode("175 5th Avenue NYC")
>>> print(location.address)
Flatiron Building, 175, 5th Avenue, Flatiron, New York, NYC, New York, ...
>>> print((location.latitude, location.longitude))
(40.7410861, -73.9896297241625)

Additionally you can specifically define you want to use Google services by using GoogleV3 class as a geolocator

>>> from geopy.geocoders import GoogleV3
>>> geolocator = GoogleV3()

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon