如何在D3世界地图中点击获取国家名称?
如何在D3世界地图点击事件中获取国家名称
问题分析
原代码存在几个关键问题导致无法获取国家信息:
- CSV数据存储错误:
Map.set()仅支持键值对,原写法无法正确存储国家代码和人口数据 - 点击事件中获取数据的方式错误:
this.name无法访问绑定的地理数据,需从D3传递的事件参数中获取 - 未给地图路径添加指定类名,导致点击事件中的元素选择器失效
修复后的完整代码
HTML部分
<script src="https://d3js.org/d3.v6.js"></script> <svg id="my_dataviz" width="400" height="300"></svg>
JavaScript部分
// 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.code, { name: d.name, pop: +d.pop }); }) ]).then(function(loadData) { let topo = loadData[0]; // 修改点击事件处理函数 let mouseClick = function(event, d) { // 重置所有国家的透明度 d3.selectAll(".Country") .transition() .duration(200) .style("opacity", .8); // 高亮点击的国家 d3.select(this) .transition() .duration(200) .style("stroke", "black") .style("opacity", 1); // 获取并打印国家信息 const countryName = d.properties.name; const countryCode = d.id; const countryPop = data.get(countryCode)?.pop || 0; console.log(`国家名称:${countryName},代码:${countryCode},人口:${countryPop}`); }; // Draw the map svg.append("g") .selectAll("path") .data(topo.features) .join("path") // 给路径添加Country类名 .attr("class", "Country") // draw each country .attr("d", d3.geoPath().projection(projection)) // set the color of each country .attr("fill", function(d) { const countryData = data.get(d.id); d.total = countryData?.pop || 0; return colorScale(d.total); }) // 绑定点击事件 .on("click", mouseClick); })
关键说明
- 数据存储修正:将CSV数据以国家代码为键存入Map,对应GeoJSON中每个国家的
d.id,方便后续关联人口数据。 - 点击事件数据获取:D3 v6中,事件处理函数的第二个参数是绑定的地理数据对象,通过
d.properties.name可直接获取国家名称,d.id获取国家代码,再通过Map取出对应的人口数据。 - DOM数据查看方式:D3绑定的数据存储在元素的
__data__属性中,而非DOM可见属性,可在控制台执行d3.select(你点击的路径元素).__data__查看完整绑定数据。
内容的提问来源于stack exchange,提问作者Terk
相关产品推荐
相关产品推荐

