Live Coding D3.js

Let's make a map!

Let's try this together. I provide you a 10-step guide to building your first map in D3.js. You can either follow along using the live code on the website or from a local web server. Here are some quick instructions on to how to get started if you choose to work locally:

Step 1: Start a project folder

Create a new folder on your Desktop and name it dlab_maps. All of the files used in the visualization should be saved into this folder.


Step 2.1 Mac Users:

You can run Python's built-in server. Open the terminal and paste:

python -m SimpleHTTPServer 8000

Once this is running, go to http://localhost:8000/.


Step 2.2 PC Users:

You have a few options, depending on what is installed on your computer. In past teaching sessions, I've found that NodeJS is easiest for Windows users. Quickly download the package from here if it applies.

Go to the command prompt (> Run > cmd), which is the Windows terminal, and paste:

npm install http-server -g
http-server

Once this is running, go to http://localhost:8000/.


Step 3: Download Spatial Data

Download and unpack this map of the United States from the National Transportation Atlas Database. Then upload the .shp file to the mapshaper website below and simply it to 10% using the slider bar. Simpifying the geometry of your data can improve download time and rendering speeds. Once simplified, you can export your shapefile (13.7 MB) to topojson (428 KB).

Step 4: Select Projection and Display Boundaries

We will use the topojson files and a map projection to portray the surface of the earth onto the x-y pixel coordinate system of our svg. Each dataset will have a unique geospatial scope, so selecting an appropriate projection to use is the first step. Here is an excellent list of the different projections provided in a extension by Jason Davies, but many more are available. For more information, visit the d3 Geo Projections page.


For our example, let's use Lambert Conformal Conic projection, centering the projection to show only the lower-48 states.

var projection = d3.geo.conicConformal()
    .rotate([98, 0]) // sets the projection's three-axis rotation to the specified angles 
    .center([0, 38]) // sets the projection's center to the specified location
    .parallels([29.5, 45.5]) // sets parallels to the specified latitudes ( degrees) 
    .scale(1000) // sets the projection's scale factor to the specified value 
    .translate([width / 2, height / 2]);

//Use projection to span from the lat-long coordinate system to the xy web browser coordinates
var xy_pixel_coordinates_array =  projection([longitude, latitude ])


Once a projection is chosen and tweaked accordingly, our map will look like this:


Copyright © Mike Taptich 2015... JK. Take what you want from here.