CHAPTER 12
Spatial indexing — Geohash, Quadtrees, S2, H3
Geohash, Quadtrees, S2, and H3 compared — how to answer 'what's near here?' across millions of points in milliseconds, and which to pick.
When you have millions of points and need to answer "what's near here?" in milliseconds, you need a spatial index. A spatial index pre-organises data by location so proximity queries skip the vast majority of records rather than scanning every row. The right choice depends on your data volume, query patterns, and database.
Geohash explorer
ttsg
Geohash
A geohash encodes a lat/lon as a short string. The longer the string, the smaller the cell. Each character adds 5 bits of precision, alternating between latitude and longitude.
| Length | Cell size (mid-latitudes) |
|---|---|
| 1 | ~5,000 km |
| 4 | ~20 km |
| 6 | ~600 m |
| 8 | ~19 m |
| 12 | ~3.7 cm |
Why it's useful: prefix matching = nearby cells. gcpvj is in gcpv, which is in gcp. Range queries on a geohash string column work directly with B-tree indexes — no special spatial extension needed.
Caveat: geohash cells are not square (they're elongated), and adjacent cells often have completely different prefixes (the famous "boundary problem" near the equator and prime meridian). Always check 8 neighbors plus center for proximity queries. If your query point sits near a cell boundary, the closest point in the world might be in a neighboring cell with a completely different hash prefix.
Quadtree
A quadtree recursively divides space into 4 quadrants:
Root: covers the whole world
├── NW
├── NE
├── SW
└── SE
├── NW
├── NE
...
Each leaf holds up to N points. Insertion and proximity queries are on average. The Web Mercator tile system is a quadtree.
Quadtrees are a standard data structures topic. The key spatial property: a quadtree at depth d has cells identical to zoom level d tiles. This is why slippy map tiles are sometimes called "tile quadkeys" — each tile's position encodes the path from root to leaf.
Continue reading "Spatial indexing — Geohash, Quadtrees, S2, H3"
You've reached the end of the free preview. Unlock all 22 paid chapters, including distance math, bearings, polygons, spatial indexing, and 3D map rendering — plus a downloadable PDF and the companion code repo.
- All 22 paid chapters with worked examples
- Downloadable PDF for offline reading
- Companion GitHub repo (JavaScript + Python)
- Free updates for life
Multiple payment options including Wise, PayPal, and bank transfer.
Related chapters
- Bounding boxes and spatial queries — the primitive that indexes build on
- Map clustering algorithms — spatial indices power most clustering
- Routing on road networks — indices accelerate path queries