geolib - Geohash encoding and decoding
geolib is a Python library providing functionality for geohash encoding, decoding, and associated operations like bounding box calculation. It is currently at version 1.0.7 and has a relatively stable, infrequent release cadence, indicating a mature and well-defined feature set.
Common errors
-
AttributeError: module 'geolib' has no attribute 'encode'
cause Users often attempt to call geohash functions directly on the top-level 'geolib' module after `import geolib`, instead of accessing them through the 'geohash' submodule.fixImport the 'geohash' submodule explicitly: `from geolib import geohash`. Then, call functions as `geohash.encode(...)`, `geohash.decode(...)`, etc. -
TypeError: float argument required, not str
cause Latitude and longitude values passed to `geohash.encode()` are strings instead of the expected numeric types (float or int).fixEnsure that `latitude` and `longitude` variables are converted to `float` or `int` before being passed to `geohash.encode()`. Example: `geohash.encode(float(lat_str), float(lon_str), precision)`.
Warnings
- gotcha The `precision` parameter in `geohash.encode()` directly controls the length and granularity of the resulting geohash. An incorrect precision can lead to hashes that are either too coarse for the desired accuracy or unnecessarily long, impacting storage and comparison efficiency.
- gotcha The return types for core functions vary: `geohash.encode` returns a string, `geohash.decode` returns a tuple `(latitude, longitude)`, and `geohash.bbox` returns a dictionary with 'n', 's', 'e', 'w' keys for the bounding box corners. This inconsistency can lead to type errors if not handled explicitly.
- gotcha While `geolib` officially supports Python >=2.7 (excluding 3.0-3.3), using it with Python 2.x in new projects is strongly discouraged. Encoding/decoding issues related to string types (unicode vs bytes) or default encodings can arise more easily in Python 2 environments, leading to subtle bugs.
Install
-
pip install geolib
Imports
- geohash
import geolib; geolib.encode(...)
from geolib import geohash
Quickstart
from geolib import geohash
# Example: Encode latitude and longitude into a geohash string
latitude = 39.04
longitude = -77.48
precision = 9 # Desired geohash length
encoded_hash = geohash.encode(latitude, longitude, precision)
print(f"Encoded geohash for ({latitude}, {longitude}) with precision {precision}: {encoded_hash}")
# Example: Decode a geohash string back to latitude and longitude
decoded_lat, decoded_lon = geohash.decode(encoded_hash)
print(f"Decoded coordinates from {encoded_hash}: Latitude={decoded_lat}, Longitude={decoded_lon}")
# Example: Get the bounding box for a geohash
bbox_coords = geohash.bbox(encoded_hash)
print(f"Bounding box for {encoded_hash}: {bbox_coords}")