pgeocode
pgeocode is a Python library for high-performance off-line querying of GPS coordinates, region name, and municipality name from postal codes. It also supports distance calculations between postal codes. The library utilizes the GeoNames database, covering 83 countries. The current version is 0.5.0. It has an active maintenance schedule with new releases that increment with feature additions and bug fixes.
Warnings
- breaking The minimum required Python version has been updated. Version 0.4.0 required Python 3.8+, while the current version 0.5.0 requires Python 3.10+.
- gotcha `GeoDistance.query_postal_code` expects postal codes as Python lists when querying multiple codes, not NumPy arrays (e.g., directly from pandas Series).
- gotcha Data files for each country are downloaded and cached locally. By default, this cache is stored in `~/.cache/pgeocode/`. If this directory is not writable or needs to be controlled (e.g., in a containerized environment), downloads might fail.
- gotcha When `Nominatim.query_location` is used for fuzzy searching by place name, the optional `thefuzz` package is required. Without it, only exact matches will be performed.
Install
-
pip install pgeocode
Imports
- pgeocode
import pgeocode
- Nominatim
from pgeocode import Nominatim
- GeoDistance
from pgeocode import GeoDistance
Quickstart
import pgeocode
import os
# Set a temporary data directory for demonstration if desired
# os.environ['PGEOCODE_DATA_DIR'] = '/tmp/pgeocode_data'
# Initialize Nominatim for a specific country (e.g., France)
nomi = pgeocode.Nominatim('fr')
# Query a single postal code
paris_13 = nomi.query_postal_code('75013')
print(f"Paris 13 details:\n{paris_13}\n")
# Query multiple postal codes
multiple_cities = nomi.query_postal_code(['75013', '69006'])
print(f"Multiple cities details:\n{multiple_cities}\n")
# Initialize GeoDistance for a specific country
dist = pgeocode.GeoDistance('fr')
# Calculate distance between two postal codes
distance_km = dist.query_postal_code('75013', '69006')
print(f"Distance between 75013 and 69006: {distance_km:.2f} km")
# Example of using query_location (requires 'thefuzz' optional dependency for fuzzy matching)
# If 'thefuzz' is not installed, it will perform exact matches.
# To install: pip install "pgeocode[fuzzy]"
# anti_data = nomi.query_location("Antibes", top_k=3)
# print(f"Antibes locations:\n{anti_data}\n")