2016-05-13 40 views
0

我使用D3.js和Leaflet,我想用不同顏色對每個圓圈進行樣式設計。我有函數檢查一個變量值,並根據該變量返回該圓圈的填充顏色。這表明只有一個驗證碼,而不是一圈後,所有陣列(點):如何將d3.js選擇設置爲單個元素?

map._initPathRoot(); 

var svg = d3.select("#map").select("svg"), 
    g = svg.append("g"); 
var feature = g.selectAll("circle") 
      .data(points) 
      .enter().append('svg') 
      .each(function (d, i) {   
        d3.select(this).selectAll('circle') 
         .data([d]) 
         .enter() 
         .append('circle') 
         .attr('r', 10) 
         .attr('stroke', 'white') 
         .attr('stroke-width', 1) 
         .attr('opacity', 0.8) 
         .style('fill', getFeatureColor(d)) //returns "red" 
      }); 
map.on("viewreset", update); 
     update(); 

     function update() { 
      feature.attr("transform", 
       function (d) { 
        if (d !== undefined) { 
         return "translate(" + 
          map.latLngToLayerPoint(d.LatLng).x + "," + 
          map.latLngToLayerPoint(d.LatLng).y + ")"; 
        } 
       } 
      ) 

     } 
function getFeatureColor(d) { 
     if(d.count>20) { 
      return "red"; 
     } 
     else {return "blue"} 
} 
+0

什麼是'getFeatureColor(d)'? – echonax

+0

函數返回例如「紅色」; – boofighter

+1

已添加功能。 – boofighter

回答

1

我認爲,沒有必要額外的SVG元素,並通過數據迭代兩次。您可以使用點陣列直接創建圓圈,如下所示。

希望這會有所幫助。

var feature = g.selectAll("circle") 
    .data(points) 
    .enter() 
    .append('circle') 
    .attr('r', 10) 
    .attr('stroke', 'white') 
    .attr('stroke-width', 1) 
    .attr('opacity', 0.8) 
    .style('fill', function(d){ return getFeatureColor(d) }); 
+0

很好,謝謝! – boofighter