1

我是 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")

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

4

1 回答 1

2

问题是您将元素附加circlepath元素中,而这在 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
于 2013-12-13T11:28:35.687 回答