Reverse Geocoding with Python and Geoapify

0

[ad_1]

Get the Geezam newsletter for tech tutorials, howtos and walkthroughs straight to your inbox

Reverse Geocoding is the process of converting map coordinates (latitude, longitude) to a physical location or address that is easily understood by humans. There any various situations where a program/app/service would need to pin a location to a specific location such as tracking, populating a map, calculating distances between locations and much much more. Let’s see how we can do reverse Geocoding with python and the Geoapify API.

Geoapify is a company that provides various “location intelligence technologies”. Let’s take a look at their reverse geocoding application programming interface and see how we can access their API using python to find the location of any set of coordinates we feed it.

Reverse Geocoding with python and Geoapify

Reverse Geocoding with Geoapify

First, sign up or log in to your Geoapify account and create a new project, name it and select the “Reverse geocoding API”. At the bottom of your project under the API keys tab after selecting reverse geocode API you should see example code for a bunch of programming languages such as Javascript, Go, Java and more. Select the tab for Python and you should see something similar to this with your own API keys.

import requests
from requests.structures import CaseInsensitiveDict

url = "https://api.geoapify.com/v1/geocode/reverse?lat=51.21709661403662&lon=6.7782883744862374&apiKey=YOUR-API-KEY-HERE"

headers = CaseInsensitiveDict()
headers["Accept"] = "application/json"

resp = requests.get(url, headers=headers)

print(resp.status_code)

Copy, paste and run the code in your favourite python programming editor and you should get a status code of “200” meaning all is well. Now let’s add to this code to play with it a little. The URL variable that the program will be sent to geoapify has three main parts.

  • an API key
  • the latitude value
  • the longitude value

Reverse Geocoding with python from a CSV file

In the modified code below we grab 5 latitude and longitude values from an exam CSV file (caribbean_airports.csv) and save them to a dictionary within a list using a For loop. Next, we do some string concatenation to create the URL to send to Geoapify with the 3 main parts needed. Next, we access the API, ask for the response in a JSON and print the parts of the JSON file we want to display on the screen.

import requests, csv
from requests.structures import CaseInsensitiveDict

#API key of your project
geoapify = "PUT-YOUR-API-KEY-HERE"

#initialise records list and lat, lon float variables
records = []
lat = 0.0
lon = 0.0

#url parts to be put together specifying JSON format
#Geoapify allows 'json', 'xml', or 'geojson' (default)
link1 = "https://api.geoapify.com/v1/geocode/reverse?"
link2 = "format=json&apiKey="

#EXAMPLE CSV file with records of 5 airports across the Caribbean
#save each airport coordinate into a dictionary array within the records list
with open("caribbean_airports.csv") as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=",")
    line_count = 0
    for row in csv_reader:
        record = {
        "lat": 0.0,
        "lon": 0.0}
        if line_count == 0:
            line_count += 1
        else:
            record["lat"] = float(row[0])
            record["lon"] = float(row[1])
            records.append(record)
            line_count += 1
        
#loop through and view each record
for cord in records:
    print(cord)
""" OUTPUT    
{'lat': 17.93644564240522, 'lon': -76.77887154784555}
{'lat': 18.576469251350392, 'lon': -72.29583239907271}
{'lat': 13.079748830120481, 'lon': -59.487715973535956}
{'lat': 12.007459857934851, 'lon': -61.78592481196946}
{'lat': 10.597751926559294, 'lon': -61.33846862517268}
"""

#create a url string that has all the parts geoapify needs
#array has five record [0] to [4]. Let's use the 1st one
lat = "lat=" + str(records[0]["lat"]) + "&"
lon = "lon=" + str(records[0]["lon"]) + "&"
url = link1 + lat + lon + link2 + geoapify

#access geoapify API with credentials
headers = CaseInsensitiveDict()
headers["Accept"] = "application/json"
resp = requests.get(url, headers=headers)

#Choose data to be displayed from JSON output received
print(resp.json()["results"][0]["name"])
print(resp.json()["results"][0]["city"])
print(resp.json()["results"][0]["country"])

""" OUTPUT
Norman Manley International Airport
Kingston
Jamaica
"""

#remove the hash sign below to see full JSON output
#print(resp.json())

The code from this tutorial is available on Github. Follow @Geezam on Twitter and subscribe to our Youtube channel for more tech tutorials, howtos and walkthroughs.

Get the Geezam newsletter for tech tutorials, howtos and walkthroughs straight to your inbox



[ad_2]

Source link

Leave A Reply

Your email address will not be published.