2013-03-09 68 views
1

我正在嘗試使用縣縣的SVG文件和每個數據的csv數據製作chloropleth地圖。我是D3新手,正在使用geoJSON的例子(謝謝Scott Murray)。 的例子中的數據聯繫,像這樣形狀:d3.js- noob-如何通過路徑ID將數據綁定到來自外部svg的路徑?

d3.json("us-states.json", function(json) { 

        //Merge the ag. data and GeoJSON 
        //Loop through once for each ag. data value 
        for (var i = 0; i < data.length; i++) { 

         var dataState = data[i].state;    //Grab state name 
         var dataValue = parseFloat(data[i].value); //Grab data value, and convert from string to float 

         //Find the corresponding state inside the GeoJSON 
         for (var j = 0; j < json.features.length; j++) { 

          var jsonState = json.features[j].properties.name; 

          if (dataState == jsonState) { 

           //Copy the data value into the JSON 
           json.features[j].properties.value = dataValue; 

           //Stop looking through the JSON 
           break; 

          } 
         }  
        } 

        //Bind data and create one path per GeoJSON feature 
        svg.selectAll("path") 
         .data(json.features) 
         .enter() 
         .append("path") 
         .attr("d", path) 
         .style("fill", function(d) { 
          //Get data value 
          var value = d.properties.value; 

          if (value) { 
           //If value exists… 
           return color(value); 
          } else { 
           //If value is undefined… 
           return "#ccc"; 
          } 
         }); 

但我在這個適應的SVG有麻煩。我不需要讓它創建路徑 - 它們已經存在,但是如何基本寫入:「if data.County ==路徑ID,將該行的數據綁定到路徑」?

任何幫助非常感謝!

回答

1

看看https://github.com/mbostock/d3/wiki/Selections#wiki-datum
這樣做:

// Where each path has an id 
var paths = d3.selectAll('.my-paths path'), 
elm, 
data = [] // your data here, 
your_criteria_here; 

data.forEach(function (x, i, a) { 

    your_criteria_here = x.criteria; 

    // No data is available for the elements in this case yet 
    // @see https://github.com/mbostock/d3/wiki/Selections#wiki-each 
    paths.each(function (d, i) { 

     // Wrap dom element in d3 selection 
     elm = d3.select(this); 

     if (elm.attr('id') == your_criteria_here) { 
      // Do something here ... 
     } 

    }); 

}); 

注意這個例子使用的[] .forEach其是ECMAScript的5特徵(@see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach