I'm trying to figure out how to retrieve the country name from a click event on the D3 world map. Despite inspecting the DOM, I can't quite understand how the country's name, code, or population is associated with the map.
The template for this project was taken from
// The svg
const svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
// Map and projection
const path = d3.geoPath();
const projection = d3.geoMercator()
.scale(70)
.center([0, 20])
.translate([width / 2, height / 2]);
// Data and color scale
let data = new Map()
const colorScale = d3.scaleThreshold()
.domain([100000, 1000000, 10000000, 30000000, 100000000, 500000000])
.range(d3.schemeBlues[7]);
// Load external data and boot
Promise.all([
d3.json("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world.geojson"),
d3.csv("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world_population.csv", function(d) {
data.set(d.name, d.code, +d.pop)
})
]).then(function(loadData) {
let topo = loadData[0]
let mouseClick = function(d) {
d3.selectAll(".Country")
.transition()
.duration(200)
.style("opacity", .8)
d3.select(this)
.transition()
.duration(200)
.style("stroke", "transparent")
console.log(this.name)
}
// Draw the map
svg.append("g")
.selectAll("path")
.data(topo.features)
.join("path")
// draw each country
.attr("d", d3.geoPath()
.projection(projection)
)
// set the color of each country
.attr("fill", function(d) {
d.total = data.get(d.id) || 0;
return colorScale(d.total);
})
})
<script src="https://d3js.org/d3.v6.js"></script>
<svg id="my_dataviz" width="400" height="300"></svg>