Compact a geohash region

Store a region as the fewest cells that cover it. geohashes_in_box returns every cell at one precision, so output grows with area divided by cell area. compact_geohashes replaces each complete group of 32 sibling cells with their parent, repeatedly, without changing the covered area.

import pygeohash as pgh

box = pgh.BoundingBox(57.0, 10.0, 58.0, 11.0)
cells = pgh.geohashes_in_box(box, precision=5)
compact = pgh.compact_geohashes(cells)
assert len(compact) < len(cells)

# Back to one precision; the set is identical.
assert set(pgh.expand_geohashes(compact, 5)) == set(cells)

Rules

  • Input is validated, lowercased and deduplicated; the result is sorted.

  • Mixed precisions are allowed. A cell already covered by a shorter cell in the input is dropped.

  • A bare string is rejected; wrap one cell in a list.

  • Thirty-one siblings are not merged: only a complete set of 32 is.

Expanding

expand_geohashes(cells, precision) turns shorter cells into all of their descendants at precision and truncates longer cells to their ancestor. A cap (max_cells, default 5,000,000) is checked before anything is generated and raises ValueError if the result would be larger; pass max_cells=None to opt out.

For any set S of precision-p cells, set(expand_geohashes(compact_geohashes(S), p)) == set(S).