API Reference¶
This section provides detailed documentation for all functions available in the PyGeoHash library.
Core Functions¶
These core functions are implemented using a high-performance C extension for maximum efficiency.
- pygeohash.encode(latitude: float, longitude: float, precision: int | Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] = 12) str[source]¶
Encode a latitude and longitude into a geohash.
- Parameters:
latitude (float) – The latitude to encode.
longitude (float) – The longitude to encode.
precision (GeohashPrecision, optional) – The number of characters in the geohash. Defaults to 12. Must be between 1 and 12, inclusive.
- Returns:
The geohash string.
- Return type:
str
- Raises:
ValueError – If the latitude or longitude values are invalid, or if the precision is not an integer or is outside the valid range (1-12). Booleans are rejected for all three arguments, even though
boolis a subclass ofint.
- pygeohash.encode_strictly(latitude: float, longitude: float, precision: int | Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] = 12) str[source]¶
Encode a latitude and longitude into a geohash.
This function currently behaves identically to
encode(): it applies the same precision/latitude/longitude validation and returns the same geohash for every input. It is retained as a separate name for API/back-compatibility (and additionally logs an error if the underlying C encoder raises). Despite its name, it does not perform any extra validation or use different midpoint handling thanencode().- Parameters:
latitude (float) – The latitude to encode.
longitude (float) – The longitude to encode.
precision (GeohashPrecision, optional) – The number of characters in the geohash. Defaults to 12. Must be between 1 and 12, inclusive.
- Returns:
The geohash string.
- Return type:
str
- Raises:
ValueError – If the latitude or longitude values are invalid, or if the precision is not an integer or is outside the valid range (1-12). Booleans are rejected for all three arguments, even though
boolis a subclass ofint.
- pygeohash.decode(geohash: str) LatLong[source]¶
Decode a geohash into a latitude and longitude.
- Parameters:
geohash (str) – The geohash string to decode. Input is case-insensitive, matching
is_valid_geohash()andget_adjacent(), so"U4PRUYD"and"U4pruYd"decode identically to"u4pruyd".- Returns:
A named tuple containing the latitude and longitude.
- Return type:
LatLong
- Raises:
ValueError – If the geohash is not a string, is not between 1 and 12 characters, or contains invalid characters.
- pygeohash.decode_exactly(geohash: str) ExactLatLong[source]¶
Decode a geohash into a latitude and longitude with error margins.
This function provides more detailed information than the standard decode function by including the error margins for both latitude and longitude.
- Parameters:
geohash (str) – The geohash string to decode. Input is case-insensitive, matching
is_valid_geohash()andget_adjacent(), so"U4PRUYD"and"U4pruYd"decode identically to"u4pruyd".- Returns:
- A named tuple containing the latitude, longitude, and their
respective error margins.
- Return type:
ExactLatLong
- Raises:
ValueError – If the geohash is not a string, is not between 1 and 12 characters, or contains invalid characters.
Data Types¶
- class pygeohash.LatLong(latitude: float, longitude: float)[source]
Bases:
NamedTupleNamed tuple representing a latitude/longitude coordinate pair.
- latitude
The latitude coordinate in decimal degrees.
- Type:
float
- longitude
The longitude coordinate in decimal degrees.
- Type:
float
Create new instance of LatLong(latitude, longitude)
- latitude: float
Alias for field number 0
- longitude: float
Alias for field number 1
- class pygeohash.ExactLatLong(latitude: float, longitude: float, latitude_error: float, longitude_error: float)[source]
Bases:
NamedTupleNamed tuple representing a latitude/longitude coordinate pair with error margins.
- latitude
The latitude coordinate in decimal degrees.
- Type:
float
- longitude
The longitude coordinate in decimal degrees.
- Type:
float
- latitude_error
The error margin for latitude in decimal degrees.
- Type:
float
- longitude_error
The error margin for longitude in decimal degrees.
- Type:
float
Create new instance of ExactLatLong(latitude, longitude, latitude_error, longitude_error)
- latitude: float
Alias for field number 0
- latitude_error: float
Alias for field number 2
- longitude: float
Alias for field number 1
- longitude_error: float
Alias for field number 3
- class pygeohash.BoundingBox(min_lat: float, min_lon: float, max_lat: float, max_lon: float)[source]
Bases:
_BoundingBoxFieldsNamed tuple representing a geospatial bounding box.
The fields interleave latitude and longitude, so the order is
(min_lat, min_lon, max_lat, max_lon)rather than the grouped(min_lat, max_lat, min_lon, max_lon). Coordinates must be finite numbers within the geographic bounds for their axis; booleans are rejected even thoughboolis a subclass ofint. Construction also rejects an inverted box (min_lat > max_latormin_lon > max_lon) with aValueError, which is what a grouped argument list produces. A degenerate box whose minimum equals its maximum on either axis is valid. Boxes spanning the antimeridian, which would needmin_lon > max_lon, are not supported.- min_lat
The minimum (southern) latitude of the box in decimal degrees. Must be between -90 and 90 and not exceed
max_lat.- Type:
float
- min_lon
The minimum (western) longitude of the box in decimal degrees. Must be between -180 and 180 and not exceed
max_lon.- Type:
float
- max_lat
The maximum (northern) latitude of the box in decimal degrees, between -90 and 90.
- Type:
float
- max_lon
The maximum (eastern) longitude of the box in decimal degrees, between -180 and 180.
- Type:
float
- Raises:
ValueError – If a coordinate is a boolean, non-finite, outside its geographic bounds, or the box has
min_lat > max_latormin_lon > max_lon.
Distance Calculations¶
- pygeohash.geohash_approximate_distance(geohash_1: str, geohash_2: str, check_validity: bool = False) float[source]¶
Calculate the approximate great-circle distance between two geohashes.
This function calculates an approximate distance based on the number of matching characters at the beginning of the geohashes. It’s faster but less accurate than haversine distance.
- Parameters:
geohash_1 (str) – The first geohash.
geohash_2 (str) – The second geohash.
check_validity (bool, optional) – Whether to check if the geohashes are valid.
False. (Defaults to)
- Returns:
The approximate distance in meters.
- Return type:
float
- Raises:
ValueError – If check_validity is True and either geohash is invalid.
Example
>>> geohash_approximate_distance("u4pruyd", "u4pruyf") 610
- pygeohash.geohash_haversine_distance(geohash_1: str, geohash_2: str) float[source]¶
Calculate the haversine great-circle distance between two geohashes.
This function provides a more accurate distance calculation using the haversine formula, which accounts for the Earth’s curvature.
- Parameters:
geohash_1 (str) – The first geohash.
geohash_2 (str) – The second geohash.
- Returns:
The distance in meters.
- Return type:
float
Example
>>> round(geohash_haversine_distance("u4pruyd", "u4pruyf"), 1) 152.7
Bounding Box Operations¶
- pygeohash.get_bounding_box(geohash: str) BoundingBox[source]¶
Calculate the bounding box for a geohash.
- Parameters:
geohash (str) – The geohash string to calculate the bounding box for.
- Returns:
- A named tuple containing the minimum and maximum latitude and longitude
values that define the bounding box of the geohash.
- Return type:
BoundingBox
Example
>>> tuple(round(value, 6) for value in get_bounding_box("u4pruyd")) (57.64801, 10.406799, 57.649384, 10.408173)
Note
The precision of the coordinates in the bounding box depends on the length of the geohash. Longer geohashes result in smaller bounding boxes with more precise coordinates.
- pygeohash.is_point_in_box(lat: float, lon: float, bbox: BoundingBox) bool[source]¶
Check if a point is within a bounding box.
- Parameters:
lat (float) – The latitude of the point to check.
lon (float) – The longitude of the point to check.
bbox (BoundingBox) – The bounding box to check against.
- Returns:
True if the point is within the bounding box, False otherwise.
- Return type:
bool
Example
>>> bbox = get_bounding_box("u4pruyd") >>> is_point_in_box(57.649, 10.407, bbox) True >>> is_point_in_box(40.0, 10.0, bbox) False
- pygeohash.is_point_in_geohash(lat: float, lon: float, geohash: str) bool[source]¶
Check if a point is within a geohash’s bounding box.
- Parameters:
lat (float) – The latitude of the point to check.
lon (float) – The longitude of the point to check.
geohash (str) – The geohash to check against.
- Returns:
True if the point is within the geohash’s bounding box, False otherwise.
- Return type:
bool
Example
>>> is_point_in_geohash(57.649, 10.407, "u4pruyd") True >>> is_point_in_geohash(40.0, 10.0, "u4pruyd") False
- pygeohash.do_boxes_intersect(bbox1: BoundingBox, bbox2: BoundingBox) bool[source]¶
Check if two bounding boxes intersect.
- Parameters:
bbox1 (BoundingBox) – The first bounding box.
bbox2 (BoundingBox) – The second bounding box.
- Returns:
True if the bounding boxes intersect, False otherwise.
- Return type:
bool
Example
>>> box1 = BoundingBox(10.0, 20.0, 30.0, 40.0) >>> box2 = BoundingBox(20.0, 30.0, 40.0, 50.0) >>> do_boxes_intersect(box1, box2) True
- pygeohash.geohashes_in_box(bbox: BoundingBox, precision: int = 6) List[str][source]¶
Find geohashes that intersect with a given bounding box.
- Parameters:
bbox (BoundingBox) – The bounding box to find geohashes for.
precision (int, optional) – The precision of the geohashes to return. Defaults to 6.
- Returns:
A list of geohashes that intersect with the bounding box.
- Return type:
List[str]
Example
>>> box = BoundingBox(57.64, 10.40, 57.65, 10.41) >>> sorted(geohashes_in_box(box, precision=5)) ['u4pru']
Note
The number of geohashes returned depends on the size of the bounding box and the precision requested. Higher precision values will result in more geohashes for the same bounding box.
Statistical Functions¶
- pygeohash.mean(geohashes: Collection[str], precision: int | Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] = 12) str[source]¶
Calculate the mean position of a collection of geohashes.
Latitude is averaged arithmetically. Longitude is averaged circularly, so a collection spanning the antimeridian is centered near ±180 rather than near the prime meridian. If the longitude vectors cancel out exactly (for example two antipodal longitudes) no unique circular mean exists, and the arithmetic mean of the longitudes is used instead.
- Parameters:
geohashes (GeohashCollection) – Collection of geohash strings. A single geohash must be wrapped in a collection, for example
["u4pruyd"].precision (GeohashPrecision, optional) – The precision of the resulting geohash. Defaults to 12.
- Returns:
- A geohash representing the mean position, or an empty string for an
empty collection.
- Return type:
str
- Raises:
TypeError – If
geohashesis a single geohash string.
Example
>>> mean(["u4pruyd", "u4pruyf", "u4pruyc"]) 'u4pruyf1m6dt'
- pygeohash.northern(geohashes: Collection[str]) str[source]¶
Find the northernmost geohash in a collection.
- Parameters:
geohashes (GeohashCollection) – Collection of geohash strings. A single geohash must be wrapped in a collection, for example
["u4pruyd"].- Returns:
The northernmost geohash.
- Return type:
str
- Raises:
TypeError – If
geohashesis a single geohash string.
Example
>>> northern(["u4pruyd", "u4pruyf", "u4pruyc"]) 'u4pruyf'
- pygeohash.southern(geohashes: Collection[str]) str[source]¶
Find the southernmost geohash in a collection.
- Parameters:
geohashes (GeohashCollection) – Collection of geohash strings. A single geohash must be wrapped in a collection, for example
["u4pruyd"].- Returns:
The southernmost geohash.
- Return type:
str
- Raises:
TypeError – If
geohashesis a single geohash string.
Example
>>> southern(["u4pruyd", "u4pruyf", "u4pruyc"]) 'u4pruyd'
- pygeohash.eastern(geohashes: Collection[str]) str[source]¶
Find the easternmost geohash in a collection.
- Parameters:
geohashes (GeohashCollection) – Collection of geohash strings. A single geohash must be wrapped in a collection, for example
["u4pruyd"].- Returns:
The easternmost geohash.
- Return type:
str
- Raises:
TypeError – If
geohashesis a single geohash string.
Example
>>> eastern(["u4pruyd", "u4pruyf", "u4pruyc"]) 'u4pruyd'
- pygeohash.western(geohashes: Collection[str]) str[source]¶
Find the westernmost geohash in a collection.
- Parameters:
geohashes (GeohashCollection) – Collection of geohash strings. A single geohash must be wrapped in a collection, for example
["u4pruyd"].- Returns:
The westernmost geohash.
- Return type:
str
- Raises:
TypeError – If
geohashesis a single geohash string.
Example
>>> western(["u4pruyd", "u4pruyf", "u4pruyc"]) 'u4pruyc'
- pygeohash.variance(geohashes: Collection[str]) float[source]¶
Calculate the variance of a collection of geohashes.
This function calculates the mean of squared distances from the mean position to each geohash in the collection.
- Parameters:
geohashes (GeohashCollection) – Collection of geohash strings. A single geohash must be wrapped in a collection, for example
["u4pruyd"].- Returns:
The variance in meters squared.
- Return type:
float
- Raises:
TypeError – If
geohashesis a single geohash string.
Example
>>> round(variance(["u4pruyd", "u4pruyf", "u4pruyc"]), 1) 6665.5
- pygeohash.std(geohashes: Collection[str]) float[source]¶
Calculate the standard deviation of a collection of geohashes.
This function calculates the square root of the variance, which represents the average distance from the mean position to each geohash in the collection.
- Parameters:
geohashes (GeohashCollection) – Collection of geohash strings. A single geohash must be wrapped in a collection, for example
["u4pruyd"].- Returns:
The standard deviation in meters.
- Return type:
float
- Raises:
TypeError – If
geohashesis a single geohash string.
Example
>>> round(std(["u4pruyd", "u4pruyf", "u4pruyc"]), 1) 81.6
Visualization Functions¶
These functions require additional dependencies that can be installed with:
pip install pygeohash[viz]
The visualization module provides tools for creating static plots with Matplotlib and interactive maps with Folium:
- pygeohash.plot_geohash(geohash: str, ax: Any | None = None, color: str = 'blue', alpha: float = 0.5, label: str | None = None, show_center: bool = False, show_label: bool = False, **kwargs: Any) Tuple[Any | None, Any | None][source]¶
Plot a single geohash on a map.
- Parameters:
geohash – The geohash string to plot
ax – Matplotlib axis to plot on (optional)
color – Color of the geohash polygon
alpha – Transparency of the geohash polygon
label – Label for the geohash (defaults to the geohash string)
show_center – Whether to show the center point of the geohash
show_label – Whether to show the label on the map
kwargs – Additional keyword arguments passed to matplotlib
- Returns:
(fig, ax) - The matplotlib figure and axis objects
- Return type:
Tuple
Examples
>>> import pygeohash as pgh >>> from pygeohash.viz import plot_geohash >>> fig, ax = plot_geohash("9q8yyk")
- pygeohash.plot_geohashes(geohashes: List[str], ax: Any | None = None, colors: str | List[str] = 'viridis', alpha: float = 0.5, labels: List[str] | None = None, show_centers: bool = False, show_labels: bool = False, **kwargs: Any) Tuple[Any | None, Any | None][source]¶
Plot multiple geohashes on a map.
- Parameters:
geohashes – List of geohash strings to plot
ax – Matplotlib axis to plot on (optional)
colors – Color or colormap name for the geohashes
alpha – Transparency of the geohash polygons
labels – Labels for the geohashes (defaults to the geohash strings)
show_centers – Whether to show the center points of the geohashes
show_labels – Whether to show the labels on the map
kwargs – Additional keyword arguments passed to matplotlib
- Returns:
(fig, ax) - The matplotlib figure and axis objects
- Return type:
Tuple
- Raises:
ValueError – If
geohashesis empty, or ifcolorsis an empty list.
Examples
>>> import pygeohash as pgh >>> from pygeohash.viz import plot_geohashes >>> fig, ax = plot_geohashes(["9q8yyk", "9q8yym", "9q8yyj"])
- pygeohash.folium_map(center_geohash: str | None = None, center: Tuple[float, float] | None = None, zoom_start: int = 13, tiles: str = 'OpenStreetMap', width: str = '100%', height: str = '100%') FoliumMapProtocol | None[source]¶
Create a folium map centered on a geohash or coordinates.
For detailed examples of how to use these functions, see the Examples section.