找到topoJSON路径的质心并使用它在D3中定位一个圆

use*_*345 4 d3.js topojson

在我的数据中,我有与国家相关的价值观.我为每个国家创建了缩放的圆圈,现在想使用cx和cy将它们放在每个国家的中心.

我使用具有国家/地区代码'ids'的topoJSON生成了一个地图,并且我的数据(cd)中有匹配的国家/地区代码.

{"type": "Polygon",
"id": 604,
"arcs": [
  [133, -473, -448, -378, -374, -413]
 ]
},
Run Code Online (Sandbox Code Playgroud)

使用D3的path.centroid(feature),如何找到每个topoJSON路径的质心?

g.selectAll("circle")
    .data(cd)
    .enter()
    .append("circle")
    .attr("class", "bubble")
    .attr("cx", 50)
    .attr("cy", 50)
    .attr("r", function(d) {
      return r(+d.Value)
    })

g.selectAll("path")
  .data(topojson.object(topology, topology.objects.countries)
    .geometries)
  .enter()
  .append("path")
  .attr("d", path)
Run Code Online (Sandbox Code Playgroud)

这里有完整的代码Plunker

Mar*_*ark 5

一种方法是这样的:

  // bind the map data
  var paths = g.selectAll("path")
    .data(topojson.object(topology, topology.objects.countries)
      .geometries)
    .enter()
    .append("path")
    .attr("d", path);

  g.selectAll("circle")
    .data(cd)
    .enter()
    .append("circle")
    .attr("class", "bubble")
    .attr("r", function(d){
      return r(+d.Value);
    })
    // using the map data
    // position a circle for matches in cd array
    .attr("transform", function(d) {
      for (var i = 0; i < paths.data().length; i++){
        var p = paths.data()[i];
        if (p.id === d["country-code"]){
          var t = path.centroid(p);
          return "translate(" + t + ")";
        }
      }
    });
Run Code Online (Sandbox Code Playgroud)

更新了plunker

征求意见

在您描述的情况下,我总是在我的数据数组中隐藏x/y位置:

g.selectAll("circle")
    .data(cd)
    .enter()
    .append("circle")
    .attr("class", "bubble")
    .attr("r", function(d){
      return r(+d.Value);
    })
    .attr("cx", function(d) {
      for (var i = 0; i < paths.data().length; i++){
        var p = paths.data()[i];
        if (p.id === d["country-code"]){
          var t = path.centroid(p);
          d.x = t[0];
          d.y = t[1];
          return d.x;
        }
      }
    })
    .attr("cy", function(d){
      return d.y;
    })
Run Code Online (Sandbox Code Playgroud)

cd数组中的对象现在将具有x/y像素位置的其他属性.

更新了两个plunker.