Published
Edited
Mar 8, 2022
5 forks
Insert cell
Insert cell
html`<h1>${ifRussia(chart)}</h1>`
Insert cell
viewof chart = {
const width = 1250;
const height = 810;
let stateselected="none";
const zoom = d3.zoom()
.scaleExtent([1, 8])
.on("zoom", zoomed);

const svg = d3.create("svg")
.attr("viewBox", [0, 0, width+350, height])
.attr("width",width)
.attr("height",height)
.on("click", reset);

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

var path = d3.geoPath().projection(
d3.geoMercator()
.fitSize([width, height], world));
g.selectAll("path")
.data(world.features, d => d.properties.brk_name)
.enter().append("path")
.attr("d", path);

const countries = g.append("g")
.selectAll("path.countries")
.data(world.features, d => d.properties.brk_name)
.join("path")
.attr("class", "countries")
.attr("d", d => path(d))
.attr("stroke", "white")
.on("click", clicked)
countries.append("title")
.text(d => d.properties.brk_name);
svg.call(zoom);

function reset() {
countries.transition().style("fill", null);
svg.property("value", "none").dispatch("input");
svg.transition().duration(750).call(
zoom.transform,
d3.zoomIdentity,
d3.zoomTransform(svg.node()).invert([width / 2, height / 2])
);
}

function clicked(event, d) {
const [[x0, y0], [x1, y1]] = path.bounds(d);
stateselected = d.properties.brk_name;
console.log(stateselected);
svg.property("value", stateselected).dispatch("input");
event.stopPropagation();
countries.transition().style("fill", null);
d3.select(this).transition().style("fill", "red");
svg.transition().duration(750).call(
zoom.transform,
d3.zoomIdentity
.translate(width / 2, height / 2)
.scale(Math.min(3, 0.9 / Math.max((x1 - x0) / width, (y1 - y0) / height)))
.translate(-(x0 + x1) / 2, -(y0 + y1) / 2),
d3.pointer(event, svg.node())
);
}
function zoomed(event) {
const {transform} = event;
g.attr("transform", transform);
g.attr("stroke-width", 1 / transform.k);
}

svg.property("value", "none").dispatch("input");
return svg.node();
}
Insert cell
Insert cell
function ifRussia (value) {
if (value=="Russia")
return "Mother Russia"
else
return value;
}
Insert cell
world= FileAttachment("world-110m.geo.json").json()
Insert cell
FileAttachment("world-110m.json").json()
Insert cell
topojson = require("topojson-client@3")
Insert cell
d3 = require("d3@6","d3-geo@3", "d3-geo-projection@4")
Insert cell
import {select} from "@jashkenas/inputs"
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