我是 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 标记中,但根本没有出现在文档中。我显然做错了什么,但我不知道是什么。