感谢 d3 和 topojson,我尝试绘制 map 。然后我用以下代码一一绘制每个国家:
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);
}
});
虽然代码运行良好,但我正在寻找一种比循环更优雅的方式来绘制这样的 map ......
最佳答案
一种方法是首先计算数据数组,然后将其映射到带有 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);
这应该与您的代码完全相同。
关于javascript - 使用 d3 和 topojson 绘制 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36595063/