API Reference 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 sorted list of geohashes that intersect with the bounding box.
- Return type:
List[str]
Example
>>> box = BoundingBox(57.64, 10.40, 57.65, 10.41) >>> 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. Cells are enumerated directly on the geohash grid instead of sampling points, so the result is returned in a deterministically sorted order that is identical across processes.
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.
Grid Interoperability¶
Pure-Python conversions between geohashes and the Bing/OSM map-tile grid,
plus an integer form of the geohash. See the Grid systems guide for
when to use each grid and what the conversions guarantee; the latitude
direction between the two grids is documented as lossy, and polar cells
require clip=True to reach the Mercator band.
- class pygeohash.Tile(x: int, y: int, zoom: int)[source]
Bases:
NamedTupleA slippy-map tile index (the
z/x/yof Bing/OSM tile caches).xandyindex the2**zoom × 2**zoomtile grid;yis counted southward from the north pole (the slippy convention), so(0, 0)is the north-west tile of the grid.Example
>>> Tile(x=1984, y=1511, zoom=12) Tile(x=1984, y=1511, zoom=12)
Create new instance of Tile(x, y, zoom)
- x: int
Alias for field number 0
- y: int
Alias for field number 1
- zoom: int
Alias for field number 2
- pygeohash.geohash_to_tile(geohash: str, clip: bool = False) Tile[source]¶
Return the slippy tile containing a geohash cell’s centre.
The zoom is
floor(5 * precision / 2). The tile column is the cell’s longitude-bit prefix — exact for every precision (an odd-precision cell is half a tile column wide and sits fully inside one column). The tile row contains the cell centre under the Web Mercator projection, so it is exact in longitude but generally lossless nowhere in latitude: geohash latitude bands are equirectangular and tile rows are not. Round-tripping cells throughtile_to_geohash()therefore shifts latitude — see the containment notes there.- Parameters:
geohash (str) – The geohash cell to map. Case-insensitive.
clip (bool, optional) – Behaviour when the cell centre lies poleward of the Web Mercator band (±85.05112878°), where tiles do not exist.
False(the default) raisesValueError;Truemaps the cell to the nearest in-band tile row (row 0 northward,2**zoom - 1southward).
- Returns:
The containing tile
(x, y, zoom).- Return type:
Tile
- Raises:
ValueError – If the geohash is not a valid 1-12 character base32 string, or (with
clip=False) if its centre lies outside the Web Mercator latitude band.
Example
>>> geohash_to_tile("ezs42") Tile(x=1984, y=1511, zoom=12) >>> geohash_to_tile("ezs42").zoom # floor(5 * 5 / 2) 12
- pygeohash.tile_to_geohash(x: int, y: int, zoom: int, precision: int | None = None) str[source]¶
Return the geohash cell containing a slippy tile’s centre.
The precision defaults to
ceil(2 * zoom / 5)(precision 1 for zoom 0): high enough that the cell’s longitude depth reaches the tile centre’s depth, so the longitude is pinned exactly, with boundary centres resolved to the lower-x, lower-y cell (west, north) per the tie rule. Latitude comes from the tile centre’s Web Mercator latitude, so the cell containing it is approximate — tile centres rarely land on equirectangular cell boundaries.Round trips are lossy in latitude by the nature of the two grids: feed the result back through
geohash_to_tile()and the row can move whenever the cell straddles a row boundary. Nothing is lost in longitude at even precision and zoom5 * precision / 2, which map cell-for-cell.- Parameters:
x (int) – Tile column,
0to2**zoom - 1.y (int) – Tile row,
0to2**zoom - 1, counted southward from the north pole (slippy convention).zoom (int) – Zoom level, 0-30.
precision (int, optional) – Precision of the returned cell, 1-12. Defaults to
ceil(2 * zoom / 5).
- Returns:
The geohash cell containing the tile centre, lowercase.
- Return type:
str
- Raises:
ValueError – If
zoomis not an integer between 0 and 30, ifxoryis not an integer within0..2**zoom - 1, or the precision is not an integer between 1 and 12.
Example
>>> tile_to_geohash(1984, 1511, 12) 'ezs42' >>> tile_to_geohash(1, 1, 2) # centre on a precision-1 boundary: resolves west 'd'
- pygeohash.geohash_to_quadkey(geohash: str, clip: bool = False) str[source]¶
Return the Bing quadkey of the tile containing a geohash cell’s centre.
The quadkey has
floor(5 * precision / 2)digits — one per tile level, each digit the tile’s x-then-y bit pair. For even precision the quadkey addresses the column the cell lives in exactly; latitude rows follow the Web Mercator projection, so the mapping is lossy in latitude for every precision (seegeohash_to_tile()).- Parameters:
geohash (str) – The geohash cell to map. Case-insensitive.
clip (bool, optional) – Polar policy for the cell centre, exactly as in
geohash_to_tile():Falseraises outside the Web Mercator band,Truemaps to the nearest in-band row.
- Returns:
The quadkey, one
0-3digit per zoom level. Never empty for a valid geohash (precision 1 already maps to zoom 2).- Return type:
str
- Raises:
ValueError – If the geohash is invalid, or (with
clip=False) if its centre lies outside the Web Mercator latitude band.
Example
>>> geohash_to_quadkey("ezs42") '031333200222'
- pygeohash.quadkey_to_geohash(quadkey: str, precision: int | None = None) str[source]¶
Return the geohash cell containing a quadkey’s tile centre.
The precision defaults to
ceil(2 * zoom / 5)(one more bit pair than the tile has levels, rounded): the cell is finer than or equal to the tile in longitude and contains the tile centre in latitude. Cells returned this way are exact in longitude (the tile centre is a dyadic point there, with boundary cases resolved west) and approximate in latitude, because the tile centre’s Web Mercator latitude rarely lands on an equirectangular geohash boundary. Round trips throughgeohash_to_quadkey()are therefore lossy in latitude for every precision.- Parameters:
quadkey (str) – The quadkey to map, one
0-3digit per zoom level. The empty string is the zoom-0 root tile.precision (int, optional) – Precision of the returned cell, 1-12. Defaults to
ceil(2 * zoom / 5)(precision 1 for the root tile).
- Returns:
The geohash cell containing the tile centre, lowercase.
- Return type:
str
- Raises:
ValueError – If the quadkey is not a string of at most 30
0-3digits, or the precision is not an integer between 1 and 12.
Example
>>> quadkey_to_geohash("031333200222") 'ezs42' >>> quadkey_to_geohash("03") # Bing's example tile (1, 1, 2): centre resolves west 'd'
- pygeohash.geohash_to_int(geohash: str) int[source]¶
Return the integer form of a geohash: base32 digits, 5 bits each, MSB first.
Lossless and exact for every valid geohash: the integer carries all
5 * precisionbits, andgeohash_from_int()with the original precision recovers the string (lowercased) exactly. This is a pure re-encoding — no grid semantics involved.- Parameters:
geohash (str) – The geohash to convert. Case-insensitive.
- Returns:
The base32 bit value,
0to2**(5 * precision) - 1.- Return type:
int
- Raises:
ValueError – If the geohash is not a valid 1-12 character base32 string.
Example
>>> geohash_to_int("ezs42") 14672002 >>> geohash_from_int(geohash_to_int("EZS42"), 5) 'ezs42'
- pygeohash.geohash_from_int(value: int, precision: int) str[source]¶
Return the geohash string encoded in an integer’s low
5 * precisionbits.The inverse of
geohash_to_int().precisionis required because the integer form carries no length: leading zero bits are indistinguishable from a shorter hash, so the caller must say how wide the value was.- Parameters:
value (int) – The bit value,
0(inclusive) to2**(5 * precision)(exclusive). Negative values and values that overflow the requested precision are rejected.precision (int) – Character count of the result, 1-12.
- Returns:
The lowercase geohash string.
- Return type:
str
- Raises:
ValueError – If
precisionis not an integer between 1 and 12, orvalueis not an integer in[0, 2**(5 * precision)).
Example
>>> geohash_from_int(14672002, 5) 'ezs42' >>> geohash_from_int(0, 1) '0'