Nearby Search: Geohash
Finding close drivers.
A ride sharing app needs to answer, which drivers are within two kilometres of this rider? There are a million drivers, all moving. Checking the distance to every one, for every request, is far too slow.

- Drivers within 2 km?
- A million moving drivers
- Checking all is too slow
Geohashing a location
A geohash turns a location into a short string. Nearby places usually share the same starting characters. It works by repeatedly halving the map, and recording which half the point is in. Run it. Two points a few streets apart in London share their first six characters. A point in Paris starts completely differently.
BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz"
def geohash(lat, lon, length=7):
lat_r, lon_r, bits, out, even = [-90, 90], [-180, 180], [], "", True
while len(out) < length:
r, v = (lon_r, lon) if even else (lat_r, lat)
mid = (r[0] + r[1]) / 2
bits.append(int(v >= mid))
r[0 if v >= mid else 1] = mid
even = not even
if len(bits) == 5:
out += BASE32[int("".join(map(str, bits)), 2)]
bits = []
return out
print("London A:", geohash(51.5072, -0.1276))
print("London B:", geohash(51.5079, -0.1281))
print("Paris: ", geohash(48.8566, 2.3522))London A: gcpvj0e London B: gcpvj0d Paris: u09tvw0
Using geohashes
To find nearby drivers, store each driver under their geohash prefix, in a fast store like Redis. For a rider, compute their geohash, and look up drivers in that cell and its eight neighbours, because the rider could be near an edge. Then check exact distances for just those few drivers.
| key | value |
|---|---|
| Store | drivers by geohash cell |
| Look up | rider's cell + 8 neighbours |
| Then | exact distance, few drivers |
| Update | as drivers move |
Summary
A geohash turns locations into strings, where shared prefixes mean nearby. Look up the rider's cell and its neighbours, then check exact distances. Next, matching riders with drivers.
Key takeaways- Location to string
- Shared prefix = nearby
- Cell + neighbours