javascript - D3 - 路径输出 0px x 0px - map 不会显示 - 不知道如何使用投影

标签 javascript json d3.js

我正在尝试在 D3 中制作世界地图。我从此链接收到了 JSON 文件:https://raw.githubusercontent.com/johan/world.geo.json/master/countries.geo.json

下面是我的代码。

  // Define SVG size
  var width = 800;
  var height = 500;

  // Define SVG attributes
  var svg = d3.select("body").append("svg")
  .attr("width", width)
  .attr("height", height);

  d3.json("/map.json", function(error, map) {
    if (error) return console.error(error);

    console.log(map);

    svg.append("g")
    .data(map.features)
    .enter().append('path')
    .attr("class", function (d) {
      return d.properties.name;
    })
    .attr('d', d3.geo.path().projection(d3.geo.mercator()));

  });

当我在本地主机上运行它时,下面是每个国家/地区显示的内容,因此我知道它正在正确读取 json 文件:

path class="Angola"d="M522.7427503528568, -- 等等

我尝试过使用不同的投影来显示 map ,但我一直无法弄清楚。每个国家/地区的路径显示为 0 像素 x 0 像素。

非常感谢任何帮助! :)

最佳答案

有两件事:

1.) 为了绑定(bind)数据,您需要 selector :

svg.append("g")
    .selectAll(".country") // <- selector
    .data(map.features)
    .enter().append('path')
    .attr("class", "country") // <- giving all paths the same class
    .attr('d', d3.geo.path().projection(d3.geo.mercator()));

2.) 您需要添加一点样式:

.country {
    fill: none;
    stroke: black;
}

您还应该注意,在您链接到的数据中有 something wrong with bermuda .

工作中example .

关于javascript - D3 - 路径输出 0px x 0px - map 不会显示 - 不知道如何使用投影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27992967/

相关文章:

javascript - 如何命名 jQuery 函数以使浏览器的后退按钮起作用?

javascript - 如何检查 chrome.storage 中是否设置了 key ?

Java 和 json 对象

java - 如何解析URL中的JSON数据?

javascript - 两个矫揉造作和一个 if 条件测试

javascript - 如何向 d3 生成的力导向图的节点添加标题属性?

javascript - angularjs-nvd3-directives 与 angular-nvd3 之间的区别

javascript - 如何将数据从组件传递到商店 Vue?

javascript - JQuery/Javascript 重新排序行

java - 如何使用 Json.simple 解析 Java 中的 JSONArray?