ST_HexagonGrid
What is ST_HexagonGrid?
ST_HexagonGrid is a set-returning PostGIS function (added in 3.1) that generates a tessellated hexagon grid covering the bounding box of an input geometry. Each row returned describes one hexagon cell, including its integer (i, j) coordinate and its polygon geometry.
ST_HexagonGrid(float size, geometry bounds) → setof record(geom geometry, i int, j int)size is the hexagon edge length in the input geometry's CRS units. The grid is aligned so hexagons are pointy-topped and tile the plane without overlap. Output hexagons share the SRID of the input bounds.
When would you use ST_HexagonGrid?
Use ST_HexagonGrid for spatial binning, heat maps, and uniform-area analysis — hexagons give a better isotropic neighbourhood than squares, making them the preferred aggregation unit for mobility, epidemiology, and retail catchment work:
1SELECT h.i, h.j, h.geom, COUNT(p.id) AS n_events
2FROM ST_HexagonGrid(500, ST_Transform(ST_MakeEnvelope(-74.1, 40.6, -73.7, 40.9, 4326), 3857)) AS h
3LEFT JOIN events p
4 ON ST_Intersects(h.geom, ST_Transform(p.geom, 3857))
5GROUP BY h.i, h.j, h.geom;It is usually paired with a projected CRS (metres) so the size has meaningful units. Use ST_Hexagon for a single hex at known (i, j) instead of scanning the full grid.
FAQs
Why do I need to call ST_HexagonGrid with a projected geometry?
Because the size argument is in CRS units. With EPSG:4326 that is degrees, giving you hexagons that are not spatially uniform. Transform the bounds to a projected CRS (metres) like UTM or EPSG:3857 so a 500-unit edge means 500 metres.
What does the (i, j) output mean?
They are the integer coordinates of each hex in the tiling. Useful as a stable key for caching or joining — two grids of the same size and bounds produce matching (i, j) values, allowing cross-time aggregation.
How many hexagons are produced?
Enough to cover the bounding box of the input bounds geometry (not just its interior). For a large bbox with a small size, this can be millions of cells — always filter the output by intersection with your area of interest.
What is the difference between ST_HexagonGrid and ST_SquareGrid?
Same pattern, different cell shape. Hexagons give more uniform neighbour distances (useful for movement or diffusion analysis); squares are faster to compute and index. Pick hex when cell-centre distance matters.