viewof chart = {
const width = 1250;
const height = 810;
let stateselected="none";
let stroke_width_original = 0;
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");
const color = d3.scaleOrdinal()
.domain(["1. High income: OECD",
"2. High income: nonOECD",
"3. Upper middle income",
"4. Lower middle income",
"5. Low income"])
.range(d3.schemeReds[5]);
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("fill",d=>color(d.properties.income_grp))
.attr("d", d => path(d))
.attr("stroke", "gray")
.on("click", clicked)
countries.append("title")
.text(d => d.properties.brk_name);
svg.call(zoom);
svg.append("g")
.attr("transform", "translate(750,0)")
.append(() => legend({color, title: "Income Group", width: 400}));
function reset() {
countries.transition().style("fill", null);
svg.selectAll(".state_name").remove();
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.attr("stroke", "gray");
//countries.attr("stroke-width", stroke_width_original);
//d3.select(this).transition().style("fill", "red");
svg.selectAll(".state_name").remove();
svg.append("text")
.attr("x", 500)
.attr("y", 0)
.style("font-size", "45px")
.text(stateselected)
.attr("class","state_name");
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();
}