Fast, static D3 maps built with Turf.js and the command-line

Combining Mike Bostock’s command-line cartography tutorial with the flexibility of Node.js

Estimated percent of undocumented residents in U.S. metro areas. Source: Pew Research Center

Recently, I needed to build a handful of U.S. state bubble maps to be embedded in a story for San Antonio Express-News. I wanted to use D3 but was concerned about slow asset loading and map rendering, especially because I’d need to iframe each map in separately due to CMS limitations.

In hopes of finding a way to export D3-generated SVGs, I did some googling.

This guy built an export button, which is pretty cool. The New York Times has SVG Crowbar, which provides similar functionality. However, the most exciting result I found was this four part article, Command-Line Cartography, by Mike Bostock.

I highly recommend Bostock’s article, from which much of this tutorial is derived. My only issue with his approach is that, for me, writing d3 code on the command line can get complicated and confusing. Here’s a snippet:

(topo2geo tracts=- \

< ca-topo.json \

| ndjson-map -r d3 -r d3=d3-scale-chromatic 'z = d3.scaleThreshold().domain([1, 10, 50, 200, 500, 1000, 2000, 4000]).range(d3.schemeOrRd[9]), d.features.forEach(f => f.properties.fill = z(f.properties.density)), d' \

| ndjson-split 'd.features'; \

topo2geo counties=- \

< ca-topo.json \

| ndjson-map 'd.properties = {"stroke": "#000", "stroke-opacity": 0.3}, d')\

| geo2svg -n --stroke none -p 1 -w 960 -h 960 \

> ca.svg

I wanted to find a solution that utilized Node.js, allowing me to still work from the command line with Bostock’s d3-geo-projection, but pass off the handling of much of the cartographical manipulation and map rendering to JavaScript. That’s where Turf.js comes in — an amazing, open source geospatial analysis tool for writing and manipulating GeoJSON.

This tutorial walks step by step through generating static maps with node and the command line. We’ll build the map seen above in SVG format, which shows the 50 metro areas with the highest percent of undocumented residents among the 100 largest U.S. metro areas.