我尝试绘制一张地图,感谢d3和topojson。然后,使用以下代码逐个绘制每个国家/地区:
d3.json("datamaps-0.5.0/src/js/data/world.topo.json", function(error, map) {
console.log(map);
for (i=0; i<map.objects.world.geometries.length; i++)
{
svg.append("path")
.attr("class", "state")
.datum(topojson.feature(map, map.objects.world.geometries[i]))
.attr("d", path);
}
});
尽管代码运行良好,但我正在寻找一种比循环绘制此类地图更优雅的方法...
最佳答案
一种方法是先计算数据数组,然后使用d3
将其映射到路径
var features= map.objects.world.geometries
.map( //.map: create a new array by applying the function below to each element of the orignal array
function(g) { //take the geometry
return topojson.feature(map, g) //and return the corresponding feature.
}
);
svg.selectAll(".state")
.data(features)
.enter()
.append("path")
.attr("class", "state")
.attr("d", path);
这应该与您的代码完全相同。