1

我正在尝试使用县的 SVG 文件和每个县的数据 csv 制作叶绿素地图。我是 D3 的新手,正在研究一个使用 geoJSON 的示例。(谢谢 Scott Murray)。该示例将数据与形状联系起来,如下所示:

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 时遇到了麻烦。我不需要让它创建路径——它们已经在那里了,但是基本上如何写:“如果 data.County == 路径 id,将该行的数据绑定到路径”?

任何帮助深表感谢!!

4

1 回答 1

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

于 2013-03-12T03:47:29.793 回答