For this post, we’ll explore some of the python packages that can be used in geocoding. Geocoding refers to retrieving geolocations (i.e) latitude & longitude by providing addresses. These details will be quite useful when we want to download satellite images of a particular location but we only have the address of the location at hand. In order to download any remote sensing images, one of the mandatory parameters is latitude and longitude.
The reverse process is called reverse geocoding, where latitude and longitude are given as inputs to retrieve the addresses. For instance, we are using an app that tracked the location with geopoints(lat & lon), but we would like to know the name of the place and area/district to which it belongs. In such scenarios, we’ll be employing reverse geocoding.
Some of the readily available python packages are:
- googlemaps api
One thing to remember while using these API's is the restriction on the number of calls permitted. For a free account, there is a limit in place. We’ll see some sample codes for how each package can be used. Let’s a sample geopoints (i.e) latitude = 34.446739 & longitude = -118.526367 and the corresponding address is 22301 Cataro Dr, Santa Clarita, CA 91350, USA.
!pip install googlemapsimport pandas as pd
Since we are accessing the details through API, the corresponding key has to be generated from the Google App and selecting the respective application such as google maps. Once we have the secrete key, we can use it for our purpose.
gmaps_key = googlemaps.Client(key="Your Key")addr = "22301 Cataro Dr, Santa Clarita, CA 91350, USA"g = gmaps_key.geocode(addr)
lat = g["geometry"]["location"]["lat"]
lon = g["geometry"]["location"]["lng"]
geopy: This is the second approach of getting the coordinates corresponding to an address.
!pip install geopy
from geopy.geocoders import Nominatim#we'll use the geopy package for getting the coordinates
from geopy.geocoders import Nominatim
Now we need to pass the address to get the coordinates,
addr = '22301 Cataro Dr, Santa Clarita, CA 91350, USA'
locator = Nominatim(user_agent='myGeocoder')
loc = locator.geocode(addr)print('The latitude is:', loc.latitude)
print('The longitude is:', loc.longitude)The latitude is: 34.446732
The longitude is: -118.52635
The retrieved value matches with the actual one.
geopy reverse geocoding: The pip install and the API reference is the same as the above code (i.e) geocoding. The only difference is, we need to provide the geolocations as input in order to get address as the output. Now applying the same through the code,
address = locator.geocode('34.446739, -118.526367')
print(address)22315, Cataro Drive, Saugus, Santa Clarita, California, 91350, United States
As we can see the address matches with the actual one.