Reverse Geocode with Python, real example with reverse_geocode.

Reverse Geocode takes a latitude/longitude coordinates 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.

Want to read it on Medium? Click here

Full resources here.

LET'S GET STARTED

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 is explained here

For this project, I am using Jupyter Notebook — the original web application for creating and sharing computational documents. It offers a simple, streamlined, document-centric experience.

The key Python library for this project is pydeck. By default, pydeck 0.6 provides basemap tiles through Carto. You can optionally use Mapbox API key, by registering for Mapbox. But, the Carto map is enough for this project.

  1. We begin with installing reverse-geocode
  pip install reverse-geocode
  pip3 install reverse-geocode
  1. and importing respective libraries
  import reverse_geocode
  import pandas as pd
  import json
  import numpy as np
  import csv
  import os
  1. 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.

  1. 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
  1. 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
  1. We can then initiate reverse_geocode passing our prepared data from coords variable and store the results in 'reversed' variable.
  # Reverse geocoding
  reversed = reverse_geocode.search(coords)
  reversed
  1. The last step would be to save the output to .csv file if needed.
  np.savetxt('reversed.csv',
    reversed,
    delimiter = ", ",
    fmt = '% s')

Happy Coding!