2012-08-29 135 views
2

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

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

回答

1

我通常采用的方法是,在choropleth map example中设置代码的方式是单独加载这两个文件,然后在需要时加入功能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); 
     }); 
} 
如果您加载文件按顺序排列,这样这是最简单的
+0

nrabinowitz的解决方案就像一个魅力。请注意,您正在引用GeoJSON对象的唯一功能ID,而不是属性。 - 数组元素和GeoJSON对象的数量必须完全相同,否则会看到控制台错误。 - 数组的位置必须与id相匹配才能显示正确的内容和正确的地图元素。 - 如果对数组排序,数据可能与正确的地图元素不匹配。 – lendegroot

+0

我正试图实现这一点。在我的发现中,除非数据重新输入,否则填充不会显示。你可否确认? –