Get Started Creating D3 Maps

JavaScript is fun, and D3 is great.

At Petrichor Studio we like to use D3 for our interactive, web-based visualizations.

As I promised recently, we’ll spend time talking about making maps with this wildly popular JavaScript visualization library.

D3 is sometimes known for imposing a learning curve on dataviz folks and JavaScript developers, but I am convinced that once you’ve tried it out several times–regardless of success or failure–familiar patterns will start emerging in the code.  There are plenty of wonderful resources and blogs that were crucial in helping me begin to understand how to harness D3, and I have included some links at the end of this post in case they might help you out, too.

Below are a couple code samples to help you get started making a simple world map in your browser.  One approach shows you how to render GeoJSON data in your browser as graphics using SVG, while the other approach uses Canvas.  They can be compared side-by-side and I encourage you to identify their similarities and differences.

The overall pattern goes like this:

  1. Set up the element where you want to render the graphics of your map: choose <svg> or <canvas> and give it an initial width and height.
  2. Establish the map projection.  We want to make a two-dimensional map, but it is typical for locations to be stored as spherical coordinates on our three-dimensional planet.  We’re going from longitude/latitude coordinates to a flat map.  D3 needs to know how we want that to happen.
  3. Create a D3 geographic path generator and tell it about the map projection.  This is the workhorse that instructs SVG or Canvas how to create two-dimensional graphics out of GeoJSON data.
  4. Load your spatial data.  These samples use a network request to load publicly available world country geometries in the TopoJSON format.  TopoJSON is more or less a special format of GeoJSON.  It just makes us take 1 extra step to convert from TopoJSON to regular GeoJSON.  No big deal.
  5. Finally, tell the geographic path generator to convert the longitude/latitude coordinates to graphics in the <svg> or <canvas>.

Simple D3 Map using SVG

See the Pen Simple D3 Map using SVG by Jacob Wasilkowski (@jwasilgeo) on CodePen.

Simple D3 Map using Canvas

See the Pen Simple D3 Map using Canvas by Jacob Wasilkowski (@jwasilgeo) on CodePen.

If you are just getting started with D3 the best advice I can give is simply what worked for me: read other people’s tutorials and code samples, all while experimenting on your own until perceived failures become replaced with tiny successes. The tiny successes will become bigger over time and failures won’t seem so scary or annoying anymore.

And some helpful resources:

Good luck! We’ll revisit these topics in more depth later with a focus on the mapping and animations of Formula 1 World Circuits.

Leave a Reply

Your email address will not be published. Required fields are marked *