[英]Draw a map with d3 and topojson
我嘗試繪制一張地圖,感謝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);
這應該與您的代碼完全相同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.