How to Retrieve Latitude and Longitude using Python’s Requests Library and OpenStreetMap Nominatim API?

Siva
2 min readMar 24, 2023

Are you looking to retrieve the latitude and longitude coordinates of various cities using Python? This blog post will guide you through a simple Python script that makes use of the OpenStreetMap Nominatim API to achieve this.

OpenStreetMap Nominatim API is a free and open-source service that provides geocoding and reverse geocoding of addresses. Geocoding is the process of converting a physical address into latitude and longitude coordinates, while reverse geocoding is the opposite process of converting latitude and longitude coordinates into a physical address.

First, let’s take a look at the code:

import requests

headers = {
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
"accept-language": "en-US,en;q=0.8",
"cache-control": "no-cache",
"pragma": "no-cache",
"sec-ch-ua": "\"Brave\";v=\"111\", \"Not(A:Brand\";v=\"8\", \"Chromium\";v=\"111\"",
"sec-ch-ua-mobile": "?1",
"sec-ch-ua-platform": "\"Android\"",
"sec-fetch-dest": "document",
"sec-fetch-mode": "navigate",
"sec-fetch-site": "none",
"sec-fetch-user": "?1",
"sec-gpc": "1",
"upgrade-insecure-requests": "1",
"cookie": "_osm_totp_token=114327"
}


data = [{"state":"MD","city":"Baltimore","country":"usa"},
{"state":"MI","city":"Highland","country":"usa"},
{"state":"SC","city":"Sumter","country":"usa"}
];

results = []

for row in data:
# Remove parentheses and state abbreviation (if present) from the city name
city = (row['city']).split("(")[0].strip().rstrip(", MA") # example MA
state = (row['state']).split("(")[0].strip()
country = (row['country']).split("()")[0].strip()

url = f"https://nominatim.openstreetmap.org/search.php?city={city}&state={state}&country={country}&format=jsonv2&addressdetails=1&limit=1"
response = requests.get(url, headers=headers)
data = response.json()
if data:
# Extract the latitude and longitude from the first result
lat = float(data[0]["lat"])
lon = float(data[0]["lon"])
# Add the city, latitude, and longitude to the results list
results.append({"lat": lat, "lon": lon})

print(results)
[{‘lat’: 39.2908816, ‘lon’: -76.610759}, {‘lat’: 44.1455678, ‘lon’: -85.2664329}, {‘lat’: 33.9204354, ‘lon’: -80.3414693}]

The first thing we do is import the requests library. This library allows us to make HTTP requests to the OpenStreetMap Nominatim API. We also set the headers for our request. These headers are necessary to prevent the API from returning an error.

Next, we define our input data. In this case, it is a list of dictionaries, each containing the state, city, and country for which we want to retrieve the latitude and longitude.

We then loop through each dictionary in our data list. For each row, we extract the city, state, and country values and format them into a URL for the Nominatim API. We use the requests.get() method to make a GET request to the API with our URL and headers. We then extract the JSON data from the response using the response.json() method.

If the API returns data, we extract the latitude and longitude from the first result and add them to a results list in the form of a dictionary with keys “lat” and “lon”.

Finally, we print the results list containing

Extra’s:
Here’s how to retrieve the URL that returns JSON:

Go to

https://nominatim.openstreetmap.org/search.php?city=Baltimore&state=MD&country=usa&format=jsonv2&addressdetails=1&limit=1

Make the request and retrieve the JSON response from the server
JSON Response:


[{"place_id":297974854,"licence":"Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright","osm_type":"relation","osm_id":133345,"boundingbox":["39.1972328","39.3719992","-76.7112977","-76.5296757"],"lat":"39.2908816","lon":"-76.610759","display_name":"Baltimore, Maryland, United States","place_rank":12,"category":"boundary","type":"administrative","importance":0.765295117264336,"icon":"https://nominatim.openstreetmap.org/ui/mapicons/poi_boundary_administrative.p.20.png","address":{"city":"Baltimore","state":"Maryland","ISO3166-2-lvl4":"US-MD","country":"United States","country_code":"us"}}]

--

--