Hi I'm fairly new to the D3 library, and I cannot figure out how to get a click event to work when I'm clicking on the country, I understand the 'd' variable contains the country information but how do I get it to console log on click. I've tried a few methods but cant figure it out. any help appreciated
const svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
// Map and projection
const projection = d3.geoNaturalEarth1()
.scale(width / 1.5 ) // Lower the num closer the zoom
.translate([200, 700]) // (Horizontal, Vertical)
// Load external data and boot
d3.json("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world.geojson").then( function(data) {
// Draw the map
svg.append("g")
.selectAll("path")
.data(data.features)
.join("path")
.attr("fill", "#348C31") // Color Of Country
.attr("d", d3.geoPath().projection(projection))
.style("stroke", "white")// Border Lines
.append("title")
.text(d => console.log(d))
//Want to run on click of country,
})
const $countyPaths = svg.append("g")
.selectAll("path")
.data(data.features)
.join("path")
$countyPaths
.attr("fill", d => color(data.get(d.id)))
.attr("d", path)
.append("title")
$countyPaths.on('click',d=>console.log(d.id))
function buttonClick() {
window.alert("Boom");
}
</script>
d3 provides the .on(event, fx(event, d)) method in order to handle events.
To log the country, you could do then the following:
svg.append("g")
.selectAll("path")
.data(data.features)
.join("path")
.attr("fill", "#348C31") // Color Of Country
.attr("d", d3.geoPath().projection(projection))
.style("stroke", "white")// Border Lines
.on("click", (_, d) => console.log(d))
Note that the first thing that the function from the event listener will receive is the event info, and the second one the data