d3.js - 更新一个 GeoJSON 元素

3

我正在制作一张地图,首先使用一个GeoJSON文件定义状态轮廓,并添加一些额外信息,例如州名。加载后,我想根据来自CSV的数据填充州并生成基于数据的工具提示,使用一些按钮和复选框(年份,不同的数据子集)。

我发现当我第二次调用状态对象上的.data()方法时,使用CSV而不是JSON文件时,路径会消失,因为它们只存在于JSON中。有没有办法只更新某些变量?是否有更好的方法将状态对象绑定到动态数据?

1个回答

2

我通常的做法,以及代码在区域地图示例中设置的方式是,分别加载两个文件,然后在需要时根据要素ID连接数据。如果您按顺序加载文件,则这种方法最简单:

// make a container
var counties = svg.append("svg:g")
    .attr("id", "counties");

// load the data you're showing
d3.json("unemployment.json", function(data) {
  // load the geo data (you could reverse the order here)
  d3.json("us-counties.json", function(json) {
    // make the map
    counties.selectAll("path")
        .data(json.features)
      .enter().append("svg:path")
        .attr("d", path);
    // now join the data, maybe in a separate function
    update(data)
  });
});

在你的update()函数中,你需要根据id对数据进行操作(如颜色等),并将这些操作应用到地图上。
update(data) {
    // look at the loaded counties
    counties.selectAll("path")
      // update colors based on data
      .attr('fill', function(d) {
        // get the id from the joined GeoJSON
        var countyId = d.id;
        // get the data point. This assumes your data is an object; if your data is
        // a CSV, you'll need to convert it to an object keyed to the id
        var datum = data[countyId];
        // now calculate your color
        return myColorScale(datum);
      });
}

nrabinowitz的解决方案非常有效。请注意,您正在引用GeoJSON对象的唯一特征ID,而不是属性。 - 数组元素和GeoJSON对象的数量必须完全相同,否则将会出现控制台错误。 - 数组位置必须与ID匹配,以显示正确的内容和正确的地图元素。 - 如果对数组进行排序,则数据可能无法与正确的地图元素匹配。 - lendegroot
我正在尝试实现这个。在我的发现中,填充不会显示,除非重新输入数据。你能确认一下吗? - Union find

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接