Pygeohash
PyGeoHash is a Python module that provides functions for encoding and decoding geohashes to and from latitude and longitude coordinates, along with utilities for performing calculations and approximations with them. It is a simple, lightweight, and dependency-free library, with core operations implemented in C for high performance. The current version is 3.2.2, and it maintains an active release cadence, having undergone a major rewrite to v3.0.0 in early 2025, focusing on performance enhancements and a license change, followed by several minor updates.
Warnings
- breaking PyGeoHash v3.0.0 introduced a complete rewrite of the core logic in CPython, removing previous dependencies like Numba and NumPy for core geohashing operations. The library also switched from a GPL-3.0 to an MIT license. Code relying on specific Numba/NumPy accelerated variants or the previous GPL license might break or behave differently.
- gotcha Input coordinates must be within valid geographical ranges: latitude between -90.0 and 90.0 degrees, and longitude between -180.0 and 180.0 degrees. Providing values outside these ranges will result in a `ValueError` for functions like `encode` and `encode_strictly`.
- gotcha Geohash strings must adhere to the base32 character set (0-9, b-h, j-k, m-n, p-z) and be between 1 and 12 characters long. Functions like `decode`, `decode_exactly`, and validation utilities (e.g., `assert_valid_geohash`) will raise a `ValueError` for invalid geohash formats (e.g., empty string, invalid characters, or excessive length).
Install
-
pip install pygeohash -
pip install pygeohash[viz]
Imports
- pygeohash
import pygeohash as pgh
Quickstart
import pygeohash as pgh
# Encode coordinates to a geohash string
latitude = 42.6
longitude = -5.6
geohash_full = pgh.encode(latitude, longitude)
print(f"Full geohash: {geohash_full}") # e.g., 'ezs42e44yx96'
# Encode with custom precision (e.g., 5 characters)
geohash_short = pgh.encode(latitude, longitude, precision=5)
print(f"Short geohash: {geohash_short}") # e.g., 'ezs42'
# Decode a geohash string back to coordinates
decoded_lat, decoded_lng = pgh.decode(geohash_short)
print(f"Decoded: Latitude={decoded_lat}, Longitude={decoded_lng}") # e.g., Latitude=42.6, Longitude=-5.6
# Calculate approximate distance between two geohashes (in meters)
distance = pgh.geohash_approximate_distance('bcd3u', 'bc83n')
print(f"Approximate distance: {distance} meters") # e.g., 625441
# Find an adjacent geohash
adjacent_geohash = pgh.get_adjacent(geohash='kd3ybyu', direction='right')
print(f"Adjacent geohash (right): {adjacent_geohash}") # e.g., 'kd3ybyv'