Algorithms · Maps & places
Hexagonal grids (H3)
Why Uber maps the world in hexagons. Squares have two kinds of neighbours. Hexagons have one. That tiny fact powers surge pricing.
The problem
Picture a busy Friday night. Thousands of riders open the app while drivers cruise around the city. Uber wants to know, neighbourhood by neighbourhood, whether there are more riders than drivers. That balance of supply and demand drives things like dynamic pricing.
To count things per neighbourhood, you first need neighbourhoods. You have to chop the whole Earth into cells, drop every rider and driver into a cell, and quickly answer "what's nearby?"
The obvious way
Use square cells, like graph paper. It's easy to code, but "nearby" gets lopsided. A square has 4 neighbours that share an edge, and 4 more that touch only at a corner. The corner ones are about 1.41 times farther from the centre. Ask for "everything one cell away" and you quietly include some neighbours that are much farther away than others.
The clever idea
Think of a honeycomb. Every cell touches exactly 6 neighbours, and every one of them is the same distance from the centre. There are no awkward corners, and the cells tile with no gaps. Uber built and open-sourced H3 (2018), a hierarchical hexagonal grid that covers the Earth with 16 resolutions, from big cells to small ones.
Our toy version below uses axial coordinates on a flat plane, not real latitude and longitude. It still shows the key trick. We bucket each driver under their cell, then answer "who's nearby?" by looking in just a handful of cells instead of checking everyone.
How the code does it
The distance function is the heart of the hex grid. Each cell is named (q, r), and the largest of three differences gives the number of steps between any two cells. The obvious scan applies it to all 40 drivers, one by one. Fine for 40, but a real city has far more.
The clever way files each driver under their cell once. Then the ring lists the 19 cells within 2 steps of the rider, and we open only those buckets. Both paths give the same answer, as the final table shows. The two bar charts at the neighbour distances show the fairness: squares give two different distances, hexes give one.
Trade-offs
Hexagons cost you simplicity. Square grids map neatly onto screens, arrays and images, while hex grids need odd coordinate systems like (q, r) and fiddly drawing code. Hexagons also can't nest perfectly inside bigger hexagons the way squares nest in squares, which matters for a hierarchy of resolutions. If your data is already pixels or a spreadsheet, or you only need rough counts, squares are simpler and good enough.
Where else you'll see it
Any place that asks "what's near this?" over a map can use the idea: bucket first, then look up neighbours. The real thing is Uber's open-source H3, written in C with bindings for many languages. Read it at github.com/uber/h3.
Why does a hex grid make "everything one step away" fairer than a square grid?
- Hexagons are bigger than squares
- All 6 neighbours are the same distance from the centre
- Hexagons need fewer coordinates
Show the answer
All 6 neighbours are the same distance from the centre. A square has edge neighbours and corner neighbours at different distances (1 vs about 1.41). A hexagon's 6 neighbours are all equally far.
- Change K = 2 to 3
- Move rider to (-3, 2)
- Change random.choices k from 40 to 400
The code
Python, with what each line means beside it. It compares the clever way with square grid cells.
import math, randomBring in math and random toolsrandom.seed(7)Fix the random seed so runs repeatS, K = 14, 2Hex size is 14 pixels; search two ringsDIRS = [(1,0),(1,-1),(0,-1),(-1,0),(-1,1),(0,1)]List the six neighbour steps of a hexagon def dist(a, b):Define distance between two hex cells dq, dr = a[0]-b[0], a[1]-b[1]Find the gap in each axis return max(abs(dq), abs(dr), abs(dq+dr))Distance is the biggest of three measures def px(c):Define turning a cell into pixels return 200 + S*math.sqrt(3)*(c[0]+c[1]/2), 200 + S*1.5*c[1]Convert cell coordinates to screen x and y def draw_hex(c, color):Define drawing one hexagon x, y = px(c)Find where the cell sits on screen circle(x, y, S*0.87, color)Paint a filled blob in its colour for i in range(6):Walk around the six corners a, b = math.radians(60*i-30), math.radians(60*i+30)Compute the angles of this edge's ends line(x+S*math.cos(a), y+S*math.sin(a), x+S*math.cos(b), y+S*math.sin(b), "#222", 1)Draw that edge in dark grey cells = [(q, r) for q in range(-6, 7) for r in range(-6, 7) if dist((q, r), (0, 0)) <= 6]Make every cell within six steps of centredrivers = random.choices(cells, k=40)Drop 40 drivers into random cellsrider = (1, -1)Choose the rider's cell scan = [d for d in drivers if dist(d, rider) <= K]Obvious way: check every single driverbuckets = {}Start an empty cell-to-drivers lookupfor d in drivers:Go through each driver buckets.setdefault(d, []).append(d)File the driver under their cellring = [(rider[0]+q, rider[1]+r) for q in range(-K, K+1) for r in range(-K, K+1) if dist((q, r), (0, 0)) <= K]List every cell within two rings of ridernear = [d for c in ring for d in buckets.get(c, [])]Collect drivers filed under those cells size(400, 400)Make the canvas 400 by 400background("#111")Paint the background darkfor c in cells:Go through every cell draw_hex(c, "#e63946" if c == rider else "#f4a261" if c in ring else "#2b2d42")Colour rider red, ring orange, rest navyfor d in drivers:Go through every driver circle(*px(d), 3, "white")Draw a white dot for them square = sorted(round(math.hypot(a, b), 2) for a in (-1, 0, 1) for b in (-1, 0, 1) if (a, b) != (0, 0))Measure square-grid neighbour distances, sortedhexes = sorted(round(math.dist(px(n), px((0, 0))) / (S*math.sqrt(3)), 2) for n in DIRS)Measure hex-grid neighbour distances, sortedshow(square, "square: 8 neighbours, 2 distances")Show square distances as barsshow(hexes, "hex: 6 neighbours, 1 distance")Show hex distances as barsshow({"scan checks": len(drivers), "cell lookups": len(ring), "same answer": sorted(scan) == sorted(near)}, "two ways, one answer")Show checks, lookups, and whether answers match- hex distance lines 6–8With axial coordinates, the number of steps between two cells is the largest of |dq|, |dr| and |dq+dr|.
- the obvious way line 24Checks every driver, so the work grows with the number of drivers, even far from the rider.
- the clever way lines 25–29Drivers are filed by cell once. A query then only opens the 19 cells in the ring.
- fair neighbours lines 38–39Square neighbours land at two different distances. Every hex neighbour is exactly 1.0 away.
Read more
- github.com: Hexagonal grids (H3)
- The real code: uber/h3
- Ask Bento: How does H3 handle the curved Earth?
- Ask Bento: What are the 16 resolutions?
- Ask Bento: How do I find a cell's neighbours?
Run it. Then change it.
The code runs right in the page and draws as it goes. Free, nothing to install.