2015-01-26 102 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'); }); 
});