Published
Edited
Dec 19, 2020
4 stars
Insert cell
Insert cell
map = {
const svg = d3.create("svg")
.attr("viewBox", [-60, 0, width, height]);
// Draw the states - we need to draw each of these features to be able
// to capture when the mouse moves in and out of the features.
svg.selectAll("path")
.data(topojson.feature(us, us.objects.states).features)
.enter()
.append("path")
.attr("fill", "#eee")
.attr("d", path)
.on("mouseover", addBoundingBox)
.on("mouseout", removeBoundingBox);

// Draw the state borders
svg.append("path")
.datum(topojson.mesh(us, us.objects.states, (a, b) => a !== b))
.attr("fill", "none")
.attr("stroke", "#999")
.attr("stroke-width", 0.5)
.attr("stroke-dasharray", "2 2")
.attr("d", path);

// Draw the nation border
svg.append("path")
.datum(topojson.mesh(us, us.objects.states, (a, b) => a === b))
.attr("fill", "none")
.attr("stroke", "gray")
.attr("stroke-width", 1)
.attr("stroke-linejoin", "round")
.attr("d", path);
function addBoundingBox(event, d) {
const bounds = path.bounds(d);
svg.append("rect")
.attr("class", "bbox")
.attr("x", bounds[0][0])
.attr("y", bounds[0][1])
.attr("width", bounds[1][0] - bounds[0][0])
.attr("height", bounds[1][1] - bounds[0][1])
.attr("fill", "none")
.attr("stroke", "red")
.attr("stroke-width", 2)
.attr("stroke-dasharray", "5 5");

const centroid = path.centroid(d);
svg.append("circle")
.attr("class", "centroid")
.attr("cx", centroid[0])
.attr("cy", centroid[1])
.attr("r", 4)
.attr("fill", "red");
}
function removeBoundingBox() {
d3.selectAll("rect.bbox").remove();
d3.selectAll("circle.centroid").remove();
}

return svg.node();
}
Insert cell
height = 610
Insert cell
width = 1100
Insert cell
path = d3.geoPath()
Insert cell
topojson.feature(us, us.objects.states)
Insert cell
Insert cell
d3 = require("d3@6")
Insert cell
topojson = require("topojson-client@3");
Insert cell
import {us} from "@d3/hexbin-map"
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more