2016-03-09 37 views
3

在我的数据中,我有与国家相关的值。我为每个国家创建了缩放圈子,现在想用cx和cy定位它们在每个国家的中心位置。查找topoJSON路径的质心并用它在D3中定位一个圆圈

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

{"type": "Polygon", 
"id": 604, 
"arcs": [ 
    [133, -473, -448, -378, -374, -413] 
] 
}, 

使用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) 

这里充分Plunker

回答

4

一种方式做到这一点会是这样的:

// 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 + ")"; 
     } 
     } 
    }); 

更新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; 
    }) 

cd阵列中的对象现在有X/Y像素位置的附加属性。

更新plunker two

+0

谢谢,使用翻译作品太棒了!我如何使用cx和cy定位来做到这一点? (我想用这些尺寸来定位我的div工具提示和文本标签) – user3821345

+0

@ user3821345,查看更新的答案。 – Mark

+0

这就是我想要的,非常感谢! – user3821345

2

代码,我会计算GeoJSON的等价的TopoJSON功能,并使用d3.geo.centroid计算每个要素的地理中心。从我以前写了一些时间的示例(绘制每个国家与比例面积的方形,集中在每个国家的心):

var geojson = topojson.feature(data, data.objects.countries).features; 

// Compute the projected centroid, area and length of the side 
// of the squares. 
geojson.forEach(function(d) { 
    d.centroid = projection(d3.geo.centroid(d)); 
    // more calculations... 
}); 

完整的例子可在http://bl.ocks.org/pnavarrc/14ed098d4072be2715db

+0

谢谢你的例子!虽然我仍然无法转换为GeoJSON https://plnkr.co/edit/f5Ps9afPdqdSCk3zUoiv?p=info获取错误,该功能不是一个功能。我是否引用了错误的对象? https://github.com/mbostock/topojson/wiki/API-Reference – user3821345