Skip to main content
100%

Projected TopoJSON

✓ Published0🌍 Public
Mmbostock
Last edited Oct 27, 2016
Created on May 10, 2013

A California county map is drawn from projected TopoJSON data, where coordinates are pre-converted to screen space so the geometry can be rendered without a geographic projection. The example uses `d3.geoPath` with a null projection and a Canvas 2D context to fill counties in light gray and stroke the mesh boundaries between distinct polygons with dark gray. The TopoJSON file was preprocessed with command-line tools like `ogr2ogr` and `topojson`, including simplification, while the rendering code loads the local `ca.json` file directly.

AI-generated description

Cartographic boundaries are commonly represented using latitude and longitude, but sometimes it’s convenient to use projected coordinates instead. This eliminates the need to project the geometry from the sphere to the plane while rendering, improving performance.

Furthermore, simplifying shapes in projected coordinates produces higher quality results, since the importance of each point is measured in area on-screen rather than on the Earth’s surface. For example, D3’s Albers USA projection displays Alaska at 0.6x its true size; simplifying in spherical coordinates preserves almost twice as much detail as needed for Alaska, whereas simplifying in projected coordinates produces a smaller file with uniform detail.

To generate a shapefile in projected coordinates, such as California Albers, use ogr2ogr’s -t_srs argument:

ogr2ogr \
	-f 'ESRI Shapefile' \
	-t_srs 'EPSG:3310' \
	counties-projected.shp \
	counties.shp

Alternatively, you can use topojson --projection to apply one of D3’s many geographic projections without needing ogr2ogr.

To convert the shapefile to TopoJSON, while simplifying, translating and scaling the geometry to fit the display, use topojson’s --width and --height arguments:

topojson \
	--width 960 \
	--height 800 \
	--margin 20 \
	-s .25 \
	-o ca.json \
	-- counties=counties-projected.shp

(For more on generating TopoJSON and manipulating shapefiles, read my Let’s Make a Map tutorial, and see the US Atlas repo for some sample shapefiles.)

Lastly, to render the projected TopoJSON, create a d3.geoPath with a null projection. This indicates that input geometry is in screen coordinates and can be displayed as-is:

var path = d3.geoPath()
    .projection(null);

Boom!

gpl-3.0 Licensed

Similar vizzes