Open In App
Related Articles

How to find longitude and latitude for a list of Regions or Country using Python

Improve Article
Save Article
Like Article

Geopy is a Python 2 and 3 client for several popular geocoding web services. Geocoding is the process to identify geographic coordinates like latitude and longitude of a given city/country/address. This is very useful during marking position on the map in data visualization. We use geopy.exec, geocodertimedout, geolocators, geopy.geocoder in the below code to fetch the results


This module does not come built-in with Python. To install it type the below command in the terminal.

pip install geopy 

Example: Let’s create a pandas dataframe containing a list of regions or countries.

# Import pandas package  
import pandas as pd 
import numpy as np
# Define a dictionary containing  data 
data = {'City':['Bangalore', 'Mumbai', 'Chennai', 'Delhi']} 
# Convert the dictionary into DataFrame 
df = pd.DataFrame(data) 
# Observe the result 


 find longitude and latitude for a list of regions/country

Now Let’s find the latitude and longitude of the following regions or countries.

from geopy.exc import GeocoderTimedOut
from geopy.geocoders import Nominatim
# declare an empty list to store
# latitude and longitude of values 
# of city column
longitude = []
latitude = []
# function to find the coordinate
# of a given city 
def findGeocode(city):
    # try and catch is used to overcome
    # the exception thrown by geolocator
    # using geocodertimedout  
        # Specify the user_agent as your
        # app name it should not be none
        geolocator = Nominatim(user_agent="your_app_name")
        return geolocator.geocode(city)
    except GeocoderTimedOut:
        return findGeocode(city)    
# each value from city column
# will be fetched and sent to
# function find_geocode   
for i in (df["City"]):
    if findGeocode(i) != None:
        loc = findGeocode(i)
        # coordinates returned from 
        # function is stored into
        # two separate list
    # if coordinate for a city not
    # found, insert "NaN" indicating 
    # missing value 

Showing the output produced as dataframe.

# now add this column to dataframe
df["Longitude"] = longitude
df["Latitude"] = latitude


 find longitude and latitude for a list of regions/country

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 16 Jul, 2020
Like Article
Save Article
Similar Reads
Complete Tutorials