At Petrichor Studio we like to use D3 for our interactive, web-based visualizations.
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
- Set up the element that will render the graphics of your map. Choose
<canvas>and give it an initial width and height.
- Establish the map projection. We want to make a two-dimensional map, but our geographical features exist on a three-dimensional planet. We’re going from longitude/latitude coordinates to a flat map and D3 needs to know how that should happen. Read up on Map Projections on the Web when you’re ready.
- 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.
- Load your spatial data. The samples below 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 takes 1 extra step to convert from TopoJSON to regular GeoJSON. No big deal.
- Use the geographic path generator to convert your data into graphics. The longitude/latitude coordinates will be drawn as map graphics in the
Simple D3 Map using SVG
Simple D3 Map using Canvas
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.
Good luck! We’ll revisit these topics in more depth by focusing on Map Projections on the Web.