Reverse Geocode with Python, real example with reverse_geocode.

PiotrDev
2 min readMar 4, 2023

--

Reverse Geocode takes a latitude/longitude coordinate and returns the country and city.

The module has a set of known geocoded locations and uses k-d tree to find the nearest neighbour efficiently. It is useful when you need to reverse geocode a large number of coordinates, so a web API is not practical.

(source: https://pypi.org/project/reverse-geocode/)

Let me show you a quick walkthrough of a little project where we need to retrieve country codes for each geo coordinates pair. We have been potentially given the task to group all geo coordinates by country and plot them on the map (plotting with deck.gl and CARTO maps explained here)

Photo by GeoJango Maps on Unsplash
  1. We begin with installing reverse-geocode,
pip install reverse-geocode
pip3 install reverse-geocode

2. and importing respective libraries.

import reverse_geocode
import pandas as pd
import json
import numpy as np
import csv
import os

3. We can quickly test reverse_geocode module.

x = 36.988287
y = 35.272027
coordinates = [(x,y)]

We have the ISO country code, city and country name returned.

4. The next step is to import our geo coordinates dataset to Pandas DataFrame and display few rows.

df = pd.read_csv('my_newDataSet.csv', index_col = 0)
df

5. As we have geo coordinates in two columns, we should prepare the data for reverse_geocode and zip the columns

# Creating a zip with latitudes and longitudes
lats=df['lat'].to_list()
lons=df['long'].to_list()
coords = list(zip(lats, lons))
coords

6. We can then initiate reverse_geocode passing our prepared data from coords variable and store the results in ‘reversed’ variable.

reversed = reverse_geocode.search(coords)

7. The last step would be to save the output to .csv file if needed.

np.savetxt('reversed.csv', 
reversed,
delimiter = ", ",
fmt = '% s')

Happy coding!

--

--

PiotrDev

15 years in Payments | Banking | Finance (FT500). MBA Warwick Business School. Full Stack Developer (JS, React, Python) | www.piotrmaciejewski.com