gpt4 book ai didi

javascript - d3/topojson 无法获取路径元素的质心

转载 作者:行者123 更新时间:2023-11-28 08:26:04 26 4
gpt4 key购买 nike

我有一个用于生成 map 的美国 JSON 文件。路径生成状态很好,但现在我想在每个路径/状态的中心添加状态名称。

这是 JSON 文件的示例

var usa = {"type": "FeatureCollection",
"features": [{ "type": "Feature", "properties": { "NAME": "Alabama"}, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ -88.124658, 30.283640 ]...

我通过附加到我已经创建的 SVG 来创建状态

var allStates = svg.selectAll("path")
.data(usa.features)
.enter()
.append("path")
.attr("d", path)

这是我尝试将州名称添加为文本的地方

var allStatesNames = svg.selectAll('text')
.data(usa.features)
.enter().append("svg:text")
.attr("transform", function(d) {
return "translate(" + path.centroid(d.geometry.coordinates) + ")"; })
.text(function(d) {return d.properties.NAME})

但我只是不断地把它拿回来

<text transform="translate(NaN,NaN)">Virginia</text>

为什么我得到 NaN 以及我应该使用什么来代替?

预先感谢您的帮助!

最佳答案

所以问题是 path.centroid 需要形状的类型和坐标,所以你不能只传入坐标。实际上,您可以使用 d 传递整个功能。

尝试将 path.centroid(d) 放入变换属性的返回中,它应该适合您。看起来 path.centroid(d.geometry) 也可以工作,但不太正确。

关于javascript - d3/topojson 无法获取路径元素的质心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22396271/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com