Geocoder
Geocoder is a simple and consistent geocoding library written in Python. It provides a unified interface for various online geocoding providers like Google, OpenStreetMap Nominatim, Mapbox, and more, abstracting away their different API structures and JSON response schemas. The current version is 1.38.1.
Warnings
- breaking As of version 1.6.0, `geocoder` removed pre-defined API keys, requiring users to pass them explicitly via the `key` parameter or through environment variables. Hardcoding keys is highly discouraged.
- gotcha External geocoding services often impose rate limits and usage quotas. Exceeding these limits can lead to HTTP 429 (Too Many Requests) or other service-specific errors, even with successful API keys.
- gotcha While `geocoder` aims to unify responses, the underlying quality, coverage, and specific details returned can vary significantly between different geocoding providers. Relying heavily on specific `raw` response structures might break if providers change their APIs.
Install
-
pip install geocoder
Imports
- geocoder
import geocoder
Quickstart
import geocoder
import os
# Geocoding an address using Google
# An API key might be required for production use or higher quotas.
# Set GOOGLE_API_KEY in your environment variables for security.
google_api_key = os.environ.get("GOOGLE_API_KEY", "")
g = geocoder.google("Mountain View, CA", key=google_api_key)
if g.ok:
print(f"Google: Latitude: {g.latlng[0]}, Longitude: {g.latlng[1]}")
print(f"Address: {g.address}")
else:
print(f"Google Geocoding failed: {g.status}")
# Reverse geocoding using OpenStreetMap Nominatim (often no API key needed for basic use)
# For production or heavy use with Nominatim, providing a unique 'user_agent' is recommended.
n = geocoder.osm([37.38605, -122.08385]) # Coordinates for Apple Park
if n.ok:
print(f"\nNominatim (Reverse): Address: {n.address}")
else:
print(f"Nominatim Reverse Geocoding failed: {n.status}")
# Example with a different provider (e.g., Mapbox), requiring an API key
mapbox_api_key = os.environ.get("MAPBOX_API_KEY", "")
if mapbox_api_key:
m = geocoder.mapbox("San Francisco, CA", key=mapbox_api_key)
if m.ok:
print(f"\nMapbox: Latitude: {m.latlng[0]}, Longitude: {m.latlng[1]}")
print(f"Address: {m.address}")
else:
print(f"Mapbox Geocoding failed: {m.status}")
else:
print("\nMAPBOX_API_KEY not set. Skipping Mapbox example.")