9951 explained code solutions for 126 technologies


javascript-d3How do I create a world map using d3.js?


Creating a world map using d3.js requires a few steps. First, you will need to get the geographic data for the world map. You can find this data at Natural Earth. After downloading the data, you will need to convert it into a GeoJSON format. You can do this using a tool like ogr2ogr.

Next, you will need to create a projection for the GeoJSON data. This is done using the d3.geo.projection function. For example, the following code creates a Mercator projection:

var projection = d3.geo.mercator()
  .scale(150)
  .translate([width / 2, height / 2]);

Once the projection is created, you can use the d3.geo.path function to create a path generator for the GeoJSON data. This is done by passing in the projection to the path generator. For example:

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

Finally, you can use the path generator to create the SVG elements for the world map. This is done by passing in the GeoJSON data to the path generator. For example:

var worldMap = svg.selectAll("path")
  .data(data.features)
  .enter()
  .append("path")
  .attr("d", path)
  .style("fill", "steelblue");

This code will create an SVG element for each feature in the GeoJSON data and set its d attribute to the path generated by the path generator. The output of this code will be an SVG world map.

Code explanation

  1. d3.geo.projection - creates a projection for the GeoJSON data
  2. d3.geo.path - creates a path generator for the GeoJSON data
  3. svg.selectAll("path") - selects all path elements in the SVG
  4. .data(data.features) - binds the GeoJSON data to the path elements
  5. .append("path") - appends a path element for each feature in the GeoJSON data
  6. .attr("d", path) - sets the d attribute of the path element to the path generated by the path generator
  7. .style("fill", "steelblue") - sets the fill color of the path element to steel blue

Helpful links

Edit this code on GitHub