javascript - 使用 d3 和 topojson 绘制 map

标签 javascript loops dictionary d3.js topojson

感谢 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/

相关文章:

javascript - Node.js 中的嵌套异步操作

c# - 如何在 .js 文件中嵌入 Razor C# 代码?

c++ - 对数组C++中的最大和最小值进行排序

python - 从列表创建多个键字典

python list append 与 extend 字典

javascript - Google Earth Engine 中带有 map() 函数的双循环

javascript - 如何在jquery中通过迭代获取值来创建JSON对象

javascript图像加载有0宽度和0高度

java - 提示用户继续不工作,java

javascript - 正则表达式在循环中的第一个匹配处停止