我正在制作一张地图,首先使用一个GeoJSON文件定义状态轮廓,并添加一些额外信息,例如州名。加载后,我想根据来自CSV的数据填充州并生成基于数据的工具提示,使用一些按钮和复选框(年份,不同的数据子集)。
我发现当我第二次调用状态对象上的.data()方法时,使用CSV而不是JSON文件时,路径会消失,因为它们只存在于JSON中。有没有办法只更新某些变量?是否有更好的方法将状态对象绑定到动态数据?
我正在制作一张地图,首先使用一个GeoJSON文件定义状态轮廓,并添加一些额外信息,例如州名。加载后,我想根据来自CSV的数据填充州并生成基于数据的工具提示,使用一些按钮和复选框(年份,不同的数据子集)。
我发现当我第二次调用状态对象上的.data()方法时,使用CSV而不是JSON文件时,路径会消失,因为它们只存在于JSON中。有没有办法只更新某些变量?是否有更好的方法将状态对象绑定到动态数据?
我通常的做法,以及代码在区域地图示例中设置的方式是,分别加载两个文件,然后在需要时根据要素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);
});
}