Reverse geocode GPS coordinates in Python.
Turn latitude and longitude into a street address, city and country with a few lines of standard-library Python, then process a whole CSV of GPS points safely.
1. Get an API key
Create a free account, verify your email and create a key in the dashboard. Store it in an environment variable instead of in your code:
export GEOCODING_API_KEY="your-key-here" # macOS / Linux
$env:GEOCODING_API_KEY = "your-key-here" # Windows PowerShellThe examples use only the Python standard library and work with Python 3.10 or newer.
2. Convert one coordinate to an address
import json
import os
from urllib.parse import urlencode
from urllib.request import urlopen
API_URL = "https://api.geocoding.info/reverse"
API_KEY = os.environ["GEOCODING_API_KEY"]
def reverse_geocode(lat, lon, zoom=18):
"""Return the place nearest to (lat, lon), or None if nothing is mapped there."""
query = urlencode({
"lat": lat, "lon": lon, "zoom": zoom,
"format": "json", "addressdetails": 1,
"accept-language": "en", "key": API_KEY,
})
with urlopen(f"{API_URL}?{query}", timeout=20) as response:
place = json.load(response)
return None if "error" in place else place
place = reverse_geocode(31.5880, 74.3107)
print(place["display_name"] if place else "No address found")Running it prints the address of the point, for example Badshahi Mosque, Fort Road, Shahi Mohallah, Walled City of Lahore, … Punjab, 54100, Pakistan. The API returns {"error": "Unable to geocode"} for points with nothing mapped nearby, which the function turns into None.
3. Pick out the city, state and country
The address object splits the result into parts. Depending on the size of the settlement, its name can be under city, town or village, so check them in order:
def city_of(address):
"""Settlements use different keys depending on their size."""
for key in ("city", "town", "village", "hamlet", "suburb"):
if key in address:
return address[key]
return None
address = place["address"]
print(city_of(address), address.get("state"), address.get("country"))Need only the city? Pass zoom=10 to reverse_geocode to get a city-level result directly.
4. Reverse geocode a CSV of GPS points
To process a file of coordinates, send requests one at a time, pause between them and retry briefly when the API answers HTTP 429 (rate limit):
import csv
import time
from urllib.error import HTTPError
def reverse_geocode_with_retry(lat, lon):
for attempt in range(3):
try:
return reverse_geocode(lat, lon)
except HTTPError as error:
if error.code != 429 or attempt == 2:
raise
time.sleep(2 ** attempt) # back off: 1s, then 2s
with open("points.csv", newline="") as source, \
open("addresses.csv", "w", newline="", encoding="utf-8") as target:
writer = csv.writer(target)
writer.writerow(["lat", "lon", "address", "city", "country"])
for row in csv.DictReader(source): # columns: lat,lon
place = reverse_geocode_with_retry(row["lat"], row["lon"])
address = place["address"] if place else {}
writer.writerow([
row["lat"], row["lon"],
place["display_name"] if place else "",
city_of(address) or "", address.get("country", ""),
])
time.sleep(1) # stay within your plan's requests-per-second limitAdjust the pause to your plan's per-second limit on the pricing page. Daily and 30-day limits are shared across all your keys.
Handling errors
urlopen raises HTTPError for non-200 responses. Check error.code: 401 means the key is wrong or missing, 429 means a rate or quota limit was reached, and 503/504 are temporary. The reverse geocoding API reference lists every error code.
- Never print or log the full request URL: it contains your key.
- Do not retry forever; give up after a few attempts and record the failure.
- Cache coordinates you have already looked up.
A complete command-line version of this script is in the geocoding-info-examples repository on GitHub.
Frequently asked questions
Do I need the geopy or requests library?
No. These examples use only the Python standard library (urllib, json and csv), so there is nothing to install. You can use requests if you prefer; the API is a plain HTTPS GET request.
How many coordinates can I reverse geocode?
It depends on your plan. Each plan has a per-second rate, a daily allowance and a 30-day allowance. The Free plan is enough for testing and small jobs; larger batches need a paid plan.
Why is the returned address not exactly at my coordinates?
Reverse geocoding returns the nearest suitable feature in OpenStreetMap, such as a building or street. Its lat and lon describe that feature, so they can differ slightly from the point you sent.
More developer guides
Map data © OpenStreetMap contributors, available under the Open Database License. Results come from Nominatim and depend on mapped coverage.