How to get the longitude and latitude of a city using Python?

To get the longitude and latitude of a city, we will use the geopy module. geopy uses third-party geocoders and other data sources to locate the coordinates of addresses, cities, countries, etc.

First of all, make sure the geopy module is installed −

pip install geopy

Using Nominatim Geocoder

In the following example, we will use the Nominatim geocoder to find the longitude and latitude of the city "Hyderabad" ?

Steps

  • Import Nominatim geocoder from geopy module.

  • Initialize the Nominatim API and use the geocode method to get the location of the input string.

  • Finally, get the latitude and longitude of the location by location.latitude and location.longitude.

Example 1

# Import the required library
from geopy.geocoders import Nominatim

# Initialize Nominatim API
geolocator = Nominatim(user_agent="MyApp")

location = geolocator.geocode("Hyderabad")

print("The latitude of the location is: ", location.latitude)
print("The longitude of the location is: ", location.longitude)

Output

The latitude of the location is: 17.360589
The longitude of the location is: 78.4740613

Reverse Geocoding (Coordinates to Location)

In this example, let's do the opposite of Example 1. We will start by providing a set of coordinates and find the city, state, and country those coordinates represent. Instead of printing the output on the console, we will create a tkinter window with four labels to display the output ?

Steps

  • Initialize the Nominatium API.

  • 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.get().

  • Create labels inside a tkinter window to display the data.

Example 2

from tkinter import *
from geopy.geocoders import Nominatim

# Create an instance of tkinter frame
win = Tk()

# Define geometry of the window
win.geometry("700x350")

# Initialize Nominatim API
geolocator = Nominatim(user_agent="MyApp")

# Latitude & Longitude input
coordinates = "17.3850 , 78.4867"

location = geolocator.reverse(coordinates)

address = location.raw['address']

# Traverse the data
city = address.get('city', '')
state = address.get('state', '')
country = address.get('country', '')

# Create a Label widget
label1=Label(text="Given Latitude and Longitude: " + coordinates, font=("Calibri", 24, "bold"))
label1.pack(pady=20)

label2=Label(text="The city is: " + city, font=("Calibri", 24, "bold"))
label2.pack(pady=20)

label3=Label(text="The state is: " + state, font=("Calibri", 24, "bold"))
label3.pack(pady=20)

label4=Label(text="The country is: " + country, font=("Calibri", 24, "bold"))
label4.pack(pady=20)

win.mainloop()

Output

Given Latitude and Longitude: 17.3850 , 78.4867 The city is: Hyderabad The state is: Telangana The country is: India

Error Handling

It's good practice to handle potential errors when geocoding ?

from geopy.geocoders import Nominatim
from geopy.exc import GeocoderTimedOut

# Initialize Nominatim API
geolocator = Nominatim(user_agent="MyApp")

try:
    location = geolocator.geocode("NonexistentCity12345")
    if location:
        print(f"Latitude: {location.latitude}")
        print(f"Longitude: {location.longitude}")
    else:
        print("Location not found!")
except GeocoderTimedOut:
    print("Geocoding service timed out")

Conclusion

The geopy module with Nominatim geocoder provides an easy way to convert city names to coordinates and vice versa. Always include error handling for robust applications and respect the geocoding service's usage limits.

Updated on: 2026-03-26T18:36:44+05:30

33K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements