Starting with a Simple Map

Learn how to display a simple map of the world and set properties such as scale, rotate, and center.

We'll cover the following...

Simple map

Our starting example will demonstrate the simple display of a world map. Our final result will look like this:

The data file for the world map is one produced by Mike Bostock’s as part of his TopoJSON work.

We’ll move through the explanation of the code in a similar process to the one we went through when highlighting the function of the Sankey diagram. Where there are areas that we have covered before, I will gloss over some details on the understanding that you will have already seen them explained in an earlier section (most likely the basic line graph example).

The code

Here is the full code:

<!DOCTYPE html>
<meta charset="utf-8">
<style>
path {
  stroke: white;
  stroke-width: 0.25px;
  fill: grey;
}
</style>
<body>
<script src="https://d3js.org/d3.v6.min.js"></script>
<script src="https://unpkg.com/topojson@3"></script>
<script>
var width = 960,
    height = 500;

var projection = d3.geoMercator()
    .center([0, 5 ])
    .scale(150)
    .rotate([-180,0]);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

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

var g = svg.append("g");

// load and display the World
d3.json("world-110m2.json").then(function(topology) {

    g.selectAll("path")
       .data(topojson.feature(topology, topology.objects.countries).features)
       .enter().append("path")
       .attr("d", path);

});

</script>
</body>
</html>
Mapping code

One of the things that struck me when I first saw the code was how small it was (the amount of code, not the world). It’s a measure of the degree of abstraction that D3 is able to provide to the process of getting data from a raw format to the screen that such a complicated task can be condensed to such an apparently small amount of code. Of course, ...