hexbin-heatmap: binning points into H3 hexagons and geohash cells, in browser and CLI

A learning project that aggregates CSV or GeoJSON points into H3 or geohash cells and draws them as a MapLibre choropleth, with a matching CLI.

Abdeldjalil Chougui (Open-Source)7 min read1 kali dilihat
hexbin-heatmap: binning points into H3 hexagons and geohash cells, in browser and CLI

Put fifty thousand points on a map and you stop seeing data. Markers pile on top of each other, the dense areas turn into one solid blob, and you cannot tell whether a spot holds ten points or ten thousand. The standard fix is to stop drawing points and draw cells instead: cut the map into a grid, count what falls in each cell, and colour the cells.

That idea is easy to say and has more moving parts than I expected. Which grid? How do you colour values that span several orders of magnitude? What happens to a cell that crosses the 180° meridian? hexbin-heatmap is the project where I worked through those questions.

It bins point data (CSV or GeoJSON) into H3 hexagons or geohash cells and shows the result as a choropleth heatmap in MapLibre, with a resolution slider. The same aggregation is available as a command-line tool that writes GeoJSON or CSV.

What it does

A web app. Open a CSV/TSV or a GeoJSON file with Point or MultiPoint features. Files are read locally and never uploaded. For CSV, the latitude and longitude columns are auto-detected (lat, latitude, y, lon, lng, longitude, x and so on), and the delimiter can be ,, ;, tab or |.

Two binning schemes. Choose H3 (resolution 0 to 15) or geohash (precision 1 to 12) with the slider, or tick "follow map zoom" and let the resolution change as you zoom.

Colour by what matters. Colour by count, or by the sum or mean of a numeric weight column. Classes can be log, quantile or linear, with 4 colour ramps.

Inspect and export. Hover a cell for its stats, and export the visible cells as GeoJSON.

A CLI with the same engine. The command-line tool runs the same aggregation code and writes GeoJSON or CSV. Each output feature has cell, count, sum and mean properties, and its id is the cell id.

How to use it

For the web app there is nothing to install. The live demo is a static site on GitHub Pages, and your files stay in the browser: https://abdeldjalilchougui.github.io/hexbin-heatmap/

To run it locally, host your own copy or use the CLI:

git clone https://github.com/AbdeldjalilChougui/hexbin-heatmap.git
cd hexbin-heatmap
pnpm install
pnpm dev                    # web app: click "Sample data" or open your own file
pnpm test                   # vitest
pnpm build                  # CLI -> dist/cli, web app -> dist/web

The production build uses the Vite base /hexbin-heatmap/ (see vite.config.ts). Change it if you serve the site from another path.

The CLI, on the bundled sample:

pnpm cli samples/points.csv --res 5 --weight value -o cells.geojson
pnpm cli samples/points.csv --mode geohash --res 4 --format csv --min-count 10
cat points.geojson | node dist/cli/index.js - -r 8      # after pnpm build

Its options:

-m, --mode <h3|geohash>     binning scheme (default h3)
-r, --res <n>               H3 resolution 0-15 or geohash precision 1-12 (default 7 / 5)
-w, --weight <name>         numeric CSV column / GeoJSON property to sum
    --lat / --lon <name>    explicit coordinate columns
    --min-count <n>         drop sparse cells
-f, --format <geojson|csv>  output format
-o, --out <file>            output file (default stdout)

What I built from scratch

All the logic lives in src/lib/, in pure TypeScript shared by the CLI and the web app:

src/lib/      pure TypeScript, shared by the CLI and the web app
  csv.ts        RFC 4180 splitter, delimiter sniffing, column detection, bad-row skipping
  geojson.ts    Point / MultiPoint / GeometryCollection extraction, weights from properties
  geohash.ts    geohash encode/decode/bounds written from scratch
  aggregate.ts  point -> cell id (h3-js latLngToCell or geohash), count/sum/mean per cell, cell polygons
  polygon.ts    antimeridian handling: split rings into a MultiPolygon at ±180°
  color.ts      ramps, linear/quantile/log class breaks, value -> colour
src/cli/      node:util parseArgs CLI
src/web/      MapLibre UI; colours via a "step" expression built from the class breaks

H3 itself comes from h3-js; I did not rewrite it. What I did write by hand is the geohash encoder and decoder, the CSV reader with delimiter sniffing, the class-break logic and the antimeridian split.

The aggregation is a single pass over the points with a Map<cell, {count, sum}>. Cells come out sorted by id, so results are deterministic: the same input always gives the same file. Cell polygons come from cellToBoundary for H3 or from the geohash bounding box, as closed [lon, lat] rings.

What I learned

The grid is a choice with consequences. Geohash cells are lat/lon rectangles, so their area varies with latitude. H3 cells are near-equal-area. If you compare counts between cells far apart in latitude, that difference matters. Writing geohash from scratch made it obvious: the cell is just a range of latitudes and a range of longitudes, nothing more.

The colour scale decides what you see. Point data is usually very uneven: a few cells hold most of the points. With linear classes, almost every cell falls into the lowest class. Quantile classes help, but they are de-duplicated, so heavily tied data (for example most cells with a count of 1) can produce fewer classes than you asked for. The log scale is the default for that reason.

The antimeridian is a real edge case. An H3 cell that straddles ±180° has a ring whose longitudes jump from one side of the world to the other. Left alone, that draws a polygon across the whole map. The project splits those rings into a MultiPolygon at the antimeridian so the GeoJSON stays valid under RFC 7946.

One library, two front ends. Because src/lib/ knows nothing about the browser or the terminal, the CLI and the web app cannot drift apart. In the web app, the colours come from a MapLibre "step" expression built from the class breaks, so the map and the legend use the same numbers.

Brute force is a good test oracle. pnpm test runs 22 tests:

  • geohash against published reference hashes, plus a decode-contains-point round trip
  • aggregation against a brute-force grouping on 3,000 random points for H3 and geohash, with total weight preserved
  • H3 cell shape and order, the antimeridian split, and resolution validation
  • CSV quoting, delimiters, column detection and bad rows; GeoJSON weights and skipped geometries
  • class breaks and classification
  • the CLI end to end on temporary files

Things to know

  • Everything runs in memory. Hundreds of thousands of points are fine, tens of millions are not.
  • Quantile classes can come out fewer than requested on heavily tied data, as described above.
  • Geohash cell area varies with latitude. Use H3 when you need cells of comparable size.
  • The basemap is tile.openstreetmap.org, which is for light personal use only under the OSM tile policy.
  • samples/points.csv (and its copy in public/) is synthetic data produced by pnpm gen:sample: Gaussian clusters around approximate Algerian city coordinates plus uniform noise. It does not represent any real measurement.

Why I built it

A pile of points hides its own pattern, and binning is the usual way out. I wanted to understand the whole path from a raw CSV to a coloured cell, not just call a ready-made layer: how a point becomes a cell id, how a grid choice changes the picture, and how class breaks change it again. Having the same code behind a web page and a CLI also means the picture you explore in the browser can be reproduced as a file by a script.

Get the code

The source, the tests and the synthetic sample are on GitHub: https://github.com/AbdeldjalilChougui/hexbin-heatmap. The code is MIT licensed. H3 is © Uber Technologies (Apache-2.0, via h3-js), and map data is © OpenStreetMap contributors (ODbL). Issues and pull requests are welcome.


Originally published at abdeldjalilchougui.biz.


Sumber artikel open-source oleh Abdeldjalil Chougui di DEV Community — Baca artikel asli. Topik: #opensource #frontend #geospatial #typescript

Sukai & bagikan artikel ini

Komentar