用d3和topojson绘制一张地图

Draw a map with d3 and topojson

本文关键字:一张 地图 d3 topojson 绘制      更新时间:2024-06-20

由于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);

这应该与您的代码完全等效。