geopy:Python Geocoding Toolbox

Posted by Afsal on 21-Apr-2023

Hi Pythonistas!

Today we will learn a package code geopy. geopy includes geocoder classes for the OpenStreetMap Nominatim, Google Geocoding API (V3), etc. Let us learn this with an example.

Installation

pip install geopy

Code

from geopy.geocoders import Nominatim

geocoder = Nominatim(user_agent='parseltongue-app')

We are creating an instance of geocoder using the OpenStreetMap. If you want Google you can use it like this

from geopy.geocoders import GoogleV3

geocoder = GoogleV3(api_key='your_google_maps_api_key_here')

Replace the google API key in the code

Geocoding Address

location = geocoder.geocode('Sansad marg, New Delhi')

print(location.latitude, location.longitude)

Output

lat:  28.6255219 long:  77.2142769

This is the address of Parliament House of India. If we check the coordinates it is correct.

Reverse Geocoding

location = geocoder.reverse("27.1751, 78.0421")

print(location.address)

Output

Taj Mahal, Taj Mahal Internal Path, Taj Ganj, Agra, Agra division, Uttar Pradesh, 282006, India

This was the coordinates for Tajmahal and we got it correct.

I hope you have learned something from this post. Please share your valuable suggestions with afsal@parseltongue.co.in