You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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);
})

关键说明

  1. 数据存储修正:将CSV数据以国家代码为键存入Map,对应GeoJSON中每个国家的d.id,方便后续关联人口数据。
  2. 点击事件数据获取:D3 v6中,事件处理函数的第二个参数是绑定的地理数据对象,通过d.properties.name可直接获取国家名称,d.id获取国家代码,再通过Map取出对应的人口数据。
  3. DOM数据查看方式:D3绑定的数据存储在元素的__data__属性中,而非DOM可见属性,可在控制台执行d3.select(你点击的路径元素).__data__查看完整绑定数据。

内容的提问来源于stack exchange,提问作者Terk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 16:15:01