Ara*_*ida 0 javascript d3.js topojson
这是一个简单但鼓舞人心的单一状态的 topojson:
https://bl.ocks.org/mbostock/7061976
它由来自仅包含该状态的 json 数据绘制,如下所示:
d3.json("va-counties.json", function(error, topo) {
if (error) throw error;
Run Code Online (Sandbox Code Playgroud)
我想做的是动态投影一个县。假设有一个键盘事件或运行这样一个函数的东西:读入解析的数据,找到县 id,并返回仅该县的 topojson 特征。上述块和我的情况之间的区别在于,我的 json 文件将包含美国的所有县,但我一次只需要 1 个县。有没有办法在 D3 中实现这一目标?
就像一个简单的试金石,对于县 id=1000,我尝试了:
var current_county = topojson.feature(topo, topo.objects.counties).filter(function(d) { return d.id=1000;})),
bounds = path.bounds(county);
Run Code Online (Sandbox Code Playgroud)
然而,无论我多么努力地处理它,我总是不断地出现错误。或者它会停止抛出错误,但仍然不能“工作”。也许.filter()不是这项工作的最佳工具?还有哪些意见?
感谢您阅读
首先你的filter语法是错误的,我认为你的意思是比较而不是赋值:
d.id === 1000
Run Code Online (Sandbox Code Playgroud)
其次,topojson.feature返回一个对象中的 GeoJSON,它不会像那样过滤。最好的办法是在以下方式中过滤它:
// filter the geometries of the topojson the structure you want
var geoCounty = topo.objects.counties.geometries.filter(function(d){
return d.id === "51750";
});
// assign it back to the topojson object
topo.objects.counties.geometries = geoCounty;
// and off you go...
var county = topojson.feature(topo, topo.objects.counties),
bounds = path.bounds(county);
Run Code Online (Sandbox Code Playgroud)
完整运行代码:
d.id === 1000
Run Code Online (Sandbox Code Playgroud)