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?
Use the geolocator. reverse() function and supply the coordinates (latitude and longitude) to get the location data. Get the address of the location using location. raw['address'] and traverse the data to find the city, state, and country using address.
The process of converting addresses to geographic information — Latitude and Longitude — to map their locations is called Geocoding. Geocoding is the computational process of transforming a physical address description to a location on the Earth's surface (spatial representation in numerical coordinates) — Wikipedia.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With