Javascript d3.js-更新GeoJSON元素

Javascript d3.js-更新GeoJSON元素,javascript,d3.js,Javascript,D3.js,我正在制作一张地图,首先用GeoJSON文件定义的路径以及一些额外的信息(如州名)定义州轮廓。加载后,我希望使用一些按钮和复选框(年份、不同的数据子集),根据csv中的数据填充状态并填充工具提示 我发现,当我第二次使用csv而不是json文件调用state对象上的.data()时,路径消失了,因为它们只存在于json中。有没有办法只更新某些变量?是否有更好的方法将状态对象绑定到动态数据?我通常采用的方法,以及在中设置代码的方法,是分别加载这两个文件,然后在需要时在feature id上连接数据。

我正在制作一张地图,首先用GeoJSON文件定义的路径以及一些额外的信息(如州名)定义州轮廓。加载后,我希望使用一些按钮和复选框(年份、不同的数据子集),根据csv中的数据填充状态并填充工具提示


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

我通常采用的方法,以及在中设置代码的方法,是分别加载这两个文件,然后在需要时在feature 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);
      });
}

纳拉比诺维茨的解决方案很有魅力。请注意,您引用的是GeoJSON对象的唯一功能id,而不是属性。-数组元素和GeoJSON对象的数量必须完全相同,否则您将看到控制台错误。-数组位置必须与id匹配,才能使用正确的映射元素显示正确的内容。-如果对数组进行排序,数据可能与正确的映射元素不匹配。我正在尝试实现这一点。除非在我的查找中重新输入数据,否则填充不会显示。你能证实吗?