Created
March 25, 2020 18:37
-
-
Save jarrettmeyer/5f57b9e1976325725c80361d3aa67d79 to your computer and use it in GitHub Desktop.
Creating a world map in D3.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Set width, height, and viewBox dimensions. | |
const width = 1600; | |
const height = 900; | |
const viewBox = [0, 0, width, height]; | |
// Create a D3 reference to the SVG element. | |
const svg = d3.select("#world-map") | |
.attr("viewBox", `${viewBox}`); | |
// Download the topology file. | |
const topology = await d3.json("/path/to/countries-50m.json"); | |
// Define the elements that we will want to draw. | |
const outline = { type: "Sphere" }; | |
const projection = d3.geoNaturalEarth1(); | |
const graticule = d3.geoGraticule10(); | |
// Set the scaling for the map. | |
const bounds = d3.geoPath(projection.fitWidth(this.width, this.outline)).bounds(this.outline); | |
const dx = Math.ceil(bounds[1][0] - bounds[0][0]); | |
const dy = Math.ceil(bounds[1][1] - bounds[0][1]); | |
const minDelta = Math.min(dx, dy); | |
projection.scale(projection.scale() * (minDelta - 1) / minDelta).precision(0.2); | |
// Define the path generator. | |
const path = d3.geoPath(projection); | |
// Get the features to draw. | |
const features = topojson.feature(topology, topology.objects.countries).features; | |
this.svg.append("path") | |
.attr("d", `${path(graticule)}`) | |
.attr("fill", "none") | |
.attr("stroke", "#e0e0e0") | |
.attr("stroke-width", 1); | |
this.svg.append("path") | |
.attr("d", `${path(this.outline)}`) | |
.attr("fill", "none") | |
.attr("stroke", "#303030") | |
.attr("stroke-width", 2); | |
this.svg.append("g") | |
.selectAll("path.feature") | |
.data((feature as any).features) | |
.join("path") | |
.classed("feature", true) | |
.attr("d", path as any) | |
.attr("stroke", "white") | |
.attr("stroke-width", 1) | |
.attr("fill", () => d3.interpolateRainbow(Math.random())); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment