更新GeoJSON元素

update a GeoJSON element

本文关键字:元素 GeoJSON 更新      更新时间:2023-09-26

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

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

我通常处理这一问题的方法,以及choropleth映射示例中设置代码的方法,是分别加载这两个文件,然后在需要时将数据连接到功能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);
      });
}