1

我正在尝试使用 D3.js 制作世界地图,但在可视化 countries.json 文件时遇到问题。

这是代码:

d3.select(window).on("resize", throttle);

var zoom = d3.behavior.zoom()
    .scaleExtent([1, 9])
    .on("zoom", move);


var width = document.getElementById('container').offsetWidth;
var height = width / 2;

var topo,projection,path,svg,g;

var graticule = d3.geo.graticule();

var tooltip = d3.select("#container").append("div")
              .attr("class", "tooltip hidden");

setup(width,height);


function setup(width,height){
  projection = d3.geo.mercator()
              .translate([(width/2), (height/2)])
              .scale( width / 2 / Math.PI);

path = d3.geo.path()
    .projection(projection);

svg = d3.select("#container").append("svg")
    .attr("width", width)
    .attr("height", height)
    .call(zoom)
    .on("click", click)
    .append("g");

g = svg.append("g");

};
d3.json("countries.json", function(error, json) {  
  var countries = topojson.object(json, json.objects.countries).features;
  topo = countries;
  draw(topo);

});

function draw(topo) {

  svg.append("path")
     .datum(graticule)
     .attr("class", "graticule")
     .attr("d", path);

这是我使用的 json 文件:

{"type":"Topology","objects":{"countries":{"bbox":[-179.99999999999986,-55.52450937299982,180.00000000000014,83.61347077000005],"type":"GeometryCollection","geometries":[{"type":"Polygon","properties":{"name":"Afghanistan"},"id":"AFG","arcs":[[0,1,2,3, ...

这是浏览器中的错误:

Uncaught TypeError: Cannot read property 'objects' of undefined

有谁知道出了什么问题以及我如何解决它?

4

2 回答 2

0

这似乎是一个浏览器安全问题,我解决了它如下:

在计算机“命令提示符”中进入文件目录并输入:

Python –m SimpleHTTPServer

这让我很头疼,但这确实有效。感谢您的帮助

于 2014-05-13T21:30:05.423 回答
0

似乎加载 JSON 文件时出现问题。在这一行...

var countries = topojson.object(json, json.objects.countries).features;

如果json未定义,它将使用“未定义”作为第一个参数,但第二个参数将完全抛出您提到的错误,因为undefined没有一个名为objects

于 2014-04-27T18:52:39.647 回答