2016-10-01 106 views
0

我遇到的主要問題是,當我嘗試在地圖內繪製點時,創建cx時,cy座標顯示爲null,但如果您檢查它, ,從我的角度來看,這是正確的。在d3.js全局圖中設置點

d3.json(meteorites, function(meteorite){ 
console.log("meteorite", meteorite.features); 
svg.selectAll("circle") 
.data(meteorite.features) 
.enter() 
.append("circle") 
.attr({ 
cx: function(d){ return projection(d.geometry.coordinates[0], d.geometry.coordinates[1])[0];}, 
cy: function(d){ return projection(d.geometry.coordinates[0], d.geometry.coordinates[1])[1];}, 
r: 5, 
fill: "red" 

}); 

和如果你喜歡看什麼我寫到這裏是鏈接到我的codepen http://codepen.io/DiazPedroAbel/pen/bwoBZd

我一直在藏漢努力沒有投影,但結果是一樣的,空,但如果我這樣做一個console.log()我得到了我期待的結果。也許我在這裏誤解了一些東西,是我第一次在d3中繪製地圖。

+0

'projection' [需要數組](https://github.com/d3/d3-3.x-api-reference/blob/master/Geo-Projections.md#_projection)'projection([d .geometry.coordinates [0],d.geometry.coordinates [1]])' – Mark

+0

我糾正了這個部分,但仍然有同樣的問題。 – coderHook

回答

4

看起來您在JSON文件中有一些條目不包含geometry對象和伴隨的geometry.coordinates數組,導致腳本失敗。我建議你安裝.data()當實現一個基本的過濾器,以確保您是有其地理座標來定義只處理節點,即不是簡單地具有以下內容:

.data(meteorite.features) 

…你可以使用.filter()雜草從你的對象的陣列條目不具有geometry對象,或geometry.coordinates陣列限定:

.data(meteorite.features.filter(function(d) { 
    return d.geometry && d.geometry.coordinates; 
})) 

參考corrected CodePen example,用下面的代碼塊更新:

d3.json(meteorites, function(meteorite){ 
    svg.selectAll("circle") 
     .data(meteorite.features.filter(function(d) { 
      return d.geometry && d.geometry.coordinates; 
     })) 
     .enter() 
     .append("circle") 
     .attr({ 
      cx: function(d){ return projection(d.geometry.coordinates)[0];}, 
      cy: function(d){ return projection(d.geometry.coordinates)[1];}, 
      r: 5, 
      fill: "red" 
    }); 
});