繁体   English   中英

使用d3和topojson绘制地图

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM