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).

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 with strict validation.

This function performs additional validation on the input coordinates before encoding them 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).

pygeohash.decode(geohash: str) LatLong[source]

Decode a geohash into a latitude and longitude.

Parameters:

geohash (str) – The geohash string to decode.

Returns:

A named tuple containing the latitude and longitude.

Return type:

LatLong

Raises:

ValueError – If the geohash is not a string, is empty, 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.

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 empty, or contains invalid characters.

Data Types

class pygeohash.LatLong(latitude: float, longitude: float)[source]

Bases: NamedTuple

Named 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: NamedTuple

Named 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: NamedTuple

Named tuple representing a geospatial bounding box.

min_lat

The minimum (southern) latitude of the box in decimal degrees.

Type:

float

min_lon

The minimum (western) longitude of the box in decimal degrees.

Type:

float

max_lat

The maximum (northern) latitude of the box in decimal degrees.

Type:

float

max_lon

The maximum (eastern) longitude of the box in decimal degrees.

Type:

float

Create new instance of BoundingBox(min_lat, min_lon, max_lat, max_lon)

max_lat: float

Alias for field number 2

max_lon: float

Alias for field number 3

min_lat: float

Alias for field number 0

min_lon: float

Alias for field number 1

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")
118.0
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

>>> geohash_haversine_distance("u4pruyd", "u4pruyf")
152.3

Geohash Navigation

pygeohash.get_adjacent(geohash: str, direction: Literal['right', 'left', 'top', 'bottom']) str[source]

Calculate the adjacent geohash in the specified direction.

Parameters:
  • geohash (str) – The input geohash string.

  • direction (Direction) – The direction to find the adjacent geohash.

  • of (Must be one) – “right”, “left”, “top”, “bottom”.

Returns:

The adjacent geohash in the specified direction.

Return type:

str

Raises:

ValueError – If the geohash length is 0 (possible when close to poles).

Example

>>> get_adjacent("u4pruyd", "top")
'u4pruyf'

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

>>> get_bounding_box("u4pruyd")
BoundingBox(min_lat=57.649, min_lon=10.407, max_lat=57.649, max_lon=10.407)

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)
>>> geohashes_in_box(box, precision=5)
['u4pru', 'u4prv']

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.

Parameters:
  • geohashes (GeohashCollection) – Collection of geohash strings.

  • precision (GeohashPrecision, optional) – The precision of the resulting geohash. Defaults to 12.

Returns:

A geohash representing the mean position.

Return type:

str

Example

>>> mean(["u4pruyd", "u4pruyf", "u4pruyc"])
'u4pruye'
pygeohash.northern(geohashes: Collection[str]) str[source]

Find the northernmost geohash in a collection.

Parameters:

geohashes (GeohashCollection) – Collection of geohash strings.

Returns:

The northernmost geohash.

Return type:

str

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.

Returns:

The southernmost geohash.

Return type:

str

Example

>>> southern(["u4pruyd", "u4pruyf", "u4pruyc"])
'u4pruyc'
pygeohash.eastern(geohashes: Collection[str]) str[source]

Find the easternmost geohash in a collection.

Parameters:

geohashes (GeohashCollection) – Collection of geohash strings.

Returns:

The easternmost geohash.

Return type:

str

Example

>>> eastern(["u4pruyd", "u4pruyf", "u4pruyc"])
'u4pruyf'
pygeohash.western(geohashes: Collection[str]) str[source]

Find the westernmost geohash in a collection.

Parameters:

geohashes (GeohashCollection) – Collection of geohash strings.

Returns:

The westernmost geohash.

Return type:

str

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.

Returns:

The variance in meters squared.

Return type:

float

Example

>>> variance(["u4pruyd", "u4pruyf", "u4pruyc"])
2500.0
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.

Returns:

The standard deviation in meters.

Return type:

float

Example

>>> std(["u4pruyd", "u4pruyf", "u4pruyc"])
50.0

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

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.