Most basic background map in d3.js

This post describes how to build a very basic background map of the world with d3.js. Note that the same kind of code would work with any geospatial data stored in geojson format. You can see many other examples in the background map section of the gallery.

Background map section


  • The Html part of the code just creates a div that will be modified by d3 later on.

  • In this example the world country boundaries are used. Data comes from here. They are provided at geojson format. If you have a shapefile format, visit the background map section to see how to proceed.

  • Note that the geo.projection plugin is used. It allows to represent the world using different projection. See this page of the gallery to see the possibilities.

  • Note: I don't understand the logic behind the .scale part.
<!DOCTYPE html>
<meta charset="utf-8">

<!-- Load d3.js -->
<script src=""></script>
<script src=""></script>
<script src=""></script>

<!-- Create an element where the map will take place -->
<svg id="my_dataviz" width="400" height="300"></svg>


// The svg
var svg ="svg"),
    width = +svg.attr("width"),
    height = +svg.attr("height");

// Map and projection
var projection = d3.geoNaturalEarth()
    .scale(width / 1.3 / Math.PI)
    .translate([width / 2, height / 2])

// Load external data and boot
d3.json("", function(data){

    // Draw the map
            .attr("fill", "#69b3a2")
            .attr("d", d3.geoPath()
            .style("stroke", "#fff")


Related blocks →

  • World Choropleth - link

  • Projection Transitions - link