How to retrieve country name for a given latitude and longitude using geopandas and naturalearthdata ?


Geopandas is an open-source library that combines the capabilities of pandas and shapely to work with geospatial data. It allows us to easily manipulate and analyze geospatial data, including shapefiles, GeoJSONs, etc.

One common task in working with geospatial data is retrieving country names for given latitude and longitude values. In this guide, we will explore how to do so using geopandas and Natural Earth Data.

Download Natural Earth 110m cultural dataset

Natural Earth Data is a public domain dataset that provides geographical data at various scales, including country boundaries, roads, cities, and more. Natural Earth Data can be downloaded for free from their website.

First step go to 1:110m Cultural Vectors and download 110m_cultural folder data and relocate the folder where you will execute your Python script.

Installing Geopandas

Before we dive into retrieving country names, let's first make sure that we have geopandas installed. To install geopandas, you can use pip for example:

pip install geopandas

Reading Natural Earth 110m cultural dataset

Let's utilize geopandas to explore the Natural Earth 110m cultural dataset:

import geopandas as gpd
import pandas as pd

from shapely.geometry import Point

df = gpd.read_file('110m_cultural')

cols = ['NAME', 'geometry']

df[cols]

How to retrieve country name for a given latitude and longitude using geopandas and naturalearthdata ?
How to retrieve country name for a given latitude and longitude using geopandas and naturalearthdata ?

Define a point with a given latitude and longitude

To retrieve the country name for a specific point, we first need to define our point using its latitude and longitude values. Let's say we want to find out which country is located at the following coordinates.

In geopandas, we can use the shapely Point class to create our point:

target_lon = 2.2137
target_lat = 46.227

point = Point(target_lon,target_lat) # create point

Verify if a point is inside a polygon associated with a specific country name

Finally, we can check if our point lies within a specific country's polygon and retrieve its name. This can be done using the contains function in geopandas:

for index, row in df.iterrows():
        if 'MultiPolygon' in row['geometry'].geom_type:
            for polygon in row['geometry'].geoms:
                if polygon.contains(point):
                    print( row['NAME'] )
        if 'Polygon' in row['geometry'].geom_type:
            polygon = row['geometry']
            if polygon.contains(point):
                print( row['NAME'] )

returns here:

France

Other methods

To retrieve country name for a given latitude and longitude see also How to retrieve country name for a given latitude and longitude using python ?

References

Image

of