【问题标题】:D3 and TopoJSON will not load in browserD3 和​​ TopoJSON 不会在浏览器中加载
【发布时间】:2015-01-23 21:29:36
【问题描述】:

我一直在使用 mbostocks github 帐户中的 D3 和 TopoJSON 示例我一直在做的 D3 和 topoJSON 工作也没有出现在浏览器或本地 nodejs http-server 中。我刚刚从 mbostocks github 复制和粘贴的示例也没有出现。这个例子如下。现在我很困惑为什么它没有出现在浏览器中。我在文件中有脚本 src 以及所需的 html 样板。如果有人可以请告诉我为什么它没有运行那会很棒。我刚开始使用 D3 和 topoJSON。谢谢!

<!DOCTYPE html>
<meta charset="utf-8">
<html>
  <head>
    <style>

      .states {
        fill: none;
        stroke: #fff;
        stroke-linejoin: round;
      }

    </style>
  </head>
  <body>
      <script src="http://d3js.org/d3.v3.min.js"></script>
      <script src="http://d3js.org/topojson.v1.min.js"></script>
      <script>

      var width = 960,
          height = 500;

      var fill = d3.scale.log()
          .domain([10, 500])
          .range(["brown", "steelblue"]);

      var path = d3.geo.path();

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

      d3.json("/mbostock/raw/4090846/us.json", function(error, us) {
        svg.append("g")
            .attr("class", "counties")
          .selectAll("path")
            .data(topojson.feature(us, us.objects.counties).features)
          .enter().append("path")
            .attr("d", path)
            .style("fill", function(d) { return fill(path.area(d)); });

        svg.append("path")
            .datum(topojson.mesh(us, us.objects.states, function(a, b) { return a.id !== b.id; }))
            .attr("class", "states")
            .attr("d", path);
      });

      </script>
  </body>

</html>

【问题讨论】:

    标签: javascript html d3.js geojson topojson


    【解决方案1】:

    您不应该在本地运行它。始终最好从 httpserver 运行它。我已将您的示例复制到 Plunker:http://plnkr.co/edit/xojc5C7RcBpQehQBdLc1?p=preview,它可以正常工作。我唯一改变的是d3.json函数中使用的URL,并复制了数据文件us.json。现在它指的是一个本地文件/mbostock/raw/4090846/us.json,我猜你在使用的位置/主机上没有它。该示例在 http://bl.ocks.org/ 上运行,因此实际文件 url 是 http://bl.ocks.org/mbostock/raw/4090846/us.json。但是由于浏览器中的跨域策略,您不能在页面上使用该 URL。

    因此,您必须做的是访问 url:http://bl.ocks.org/mbostock/raw/4090846/us.json 并将该文件另存为 us.json,与 index.html 所在的目录相同。然后像我在 Plunker 中所做的那样,将函数 d3.json() 中的 URL 更改为 us.json。自己看看,这段代码没有错。我猜脚本根本找不到 JSON 文件,所以它不会绘制任何东西,因为它没有要绘制的数据。您可以在控制台窗口中看到,它应该会抛出错误:“GET http://yourhost/mbostock/raw/4090846/us.json 404 (Not Found)”

    顺便说一句:Pl​​unker 也有一个下载按钮,因此它可以将 Plunker 中使用的所有文件下载到一个压缩的 zip 文件中。你也可以用那个。祝你好运!

    【讨论】:

      猜你喜欢
      • 2016-11-07
      • 1970-01-01
      • 2013-05-27
      • 1970-01-01
      • 2015-11-08
      • 2016-07-06
      • 1970-01-01
      • 2016-01-17
      • 2019-09-28
      相关资源
      最近更新 更多