2015-01-26 103 views
0

我试图在D3中创建我的第一张地图。地图显示正常,但我现在想要循环遍历每个附加到我的SVG的路径。这是我正在处理的代码:使用.each循环遍历路径D3

var path = d3.geo.path() 
        .projection(projection); 
//Create SVG element 
var svg = d3.select("body") 
      .append("svg") 
      .attr("width", w) 
      .attr("height", h); 


//Load in GeoJSON data 
d3.json("/data/friesland.json", function (json) { 

    //Bind data and create one path per GeoJSON feature 
     svg.selectAll("path") 
     .data(json.features) 
     .enter() 
     .append("path") 
     .attr("d", path) 
     .attr('fill', 'rgba(29,91,85,1)') 
     .attr('stroke', 'white') 
     .attr('stroke-width', 1); 

}); 

svg.selectAll('path').each(function (d, i) { console.log('test'); }); 

似乎没有绑定到svg的路径,我该如何更改它? 谢谢!

+0

''d3.json'' *异步执行*。试着把你最后一行放在你传递给'd3.json'的'function'中。 – mdml 2015-01-26 18:57:56

+0

感谢您的快速回复,这很有道理! – Miriam 2015-01-26 18:59:52

+0

我添加了我的评论作为答案。 – mdml 2015-01-26 19:22:39

回答

0

d3.json执行asychronously(参见docs)。请尝试选择<path>是你传递给d3.json里面的功能,像这样:

d3.json("/data/friesland.json", function (json) { 

//Bind data and create one path per GeoJSON feature 
svg.selectAll("path") 
    .data(json.features) 
    .enter() 
    .append("path") 
    .attr("d", path) 
    .attr('fill', 'rgba(29,91,85,1)') 
    .attr('stroke', 'white') 
    .attr('stroke-width', 1); 


svg.selectAll('path').each(function (d, i) { console.log('test'); }); 

}); 

现在你只会选择<path> S中的SVG已被填充后。

0

正如mdml建议的那样,您希望将您的selectAll放入回调函数中,以便在发生绑定之前发生。

var path = d3.geo.path() 
       .projection(projection); 
var svg = d3.select("body") 
     .append("svg") 
     .attr("width", w) 
     .attr("height", h); 


d3.json("/data/friesland.json", function (json) { 

    svg.selectAll("path") 
    .data(json.features) 
    .enter() 
    .append("path") 
    .attr("d", path) 
    .attr('fill', 'rgba(29,91,85,1)') 
    .attr('stroke', 'white') 
    .attr('stroke-width', 1); 
    svg.selectAll('path').each(function (d, i) { console.log('test'); }); 
});