简体   繁体   English

使用d3和topojson绘制地图

[英]Draw a map with d3 and topojson

I try to draw a map thank to d3 and topojson. 我尝试绘制一张地图,感谢d3和topojson。 Then I draw each country one by one with this code : 然后,使用以下代码逐个绘制每个国家/地区:

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);
    }
});

Although the code works well, I'm looking for a more elegant way than a loop to draw a such map... 尽管代码运行良好,但我正在寻找一种比循环绘制此类地图更优雅的方法...

One way to do it is to first compute your data array, then map it to the paths with d3 一种方法是首先计算数据数组,然后使用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);

This should be exactly equivalent to your code. 这应该与您的代码完全相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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