未显示在数据生成的d3形状顶部的套印格式

Overlays not showing up on top of data-generated d3 shapes

本文关键字:顶部 格式 d3 数据 显示      更新时间:2023-09-26

我是d3.js的新手。我使用topoJSON数据来渲染地图,到目前为止效果很好。现在,我想在每个国家/地区的顶部覆盖一些数据,如文本或圆圈,我遇到了麻烦。我有类似的代码:

var countries = g.append("g")
    .attr("id", "countries")
    .selectAll("path")
    .data(topojson.feature(collection, collection.objects.countries).features)
    .enter().append("path")
    .attr("d", path)
    .style("fill", colorize)
    .attr("class", "country")
    .on("click", clicked)

它正确地渲染了我的地图。为了在上面覆盖一些圆圈,我做了以下操作:

countries
    .append("circle")
    .attr("r", function(d, i, j) {
      return 10; // for now
    })
    // getCentroid below is a function that returns the 
    // center of the poligon/path bounding box
    .attr("cy", function(d, i, j) { return getCentroid(countries[0][j])[0]})
    .attr("cx", function(d, i, j) { return getCentroid(countries[0][j])[1]})
    .style("fill", "red")

这相当麻烦(特别是访问countries数组的方式),但它成功地为代表一个国家的每条路径添加了一个圆圈。问题是这个圆圈存在于SVG标记中,但根本没有显示在文档中。我显然做错了什么,但我不知道是什么。

问题是将circle元素附加到path元素上,这在SVG中是做不到的。您需要将它们附加到父g元素中。代码看起来像这样。

var countries = g.selectAll("g.countries")
  .data(topojson.feature(collection, collection.objects.countries).features)
  .enter().append("g")
  .attr("id", "countries");
countries.append("path")
  .datum(function(d) { return d; })
  .attr("d", path)
  // etc
countries.append("circles")
  // etc