使用D3.js可视化世界地图,但无法可视化json文件

Visualizing world map using D3.js but cant visualize the json file

本文关键字:可视化 json 文件 D3 js 世界地图 使用      更新时间:2023-09-26

我正在尝试用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

有人知道出了什么问题,我该怎么解决吗?

加载JSON文件时出现问题。在这行。。。

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

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

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

在计算机"命令提示符"中,转到文件目录并输入:

Python –m SimpleHTTPServer

这让我头疼了一小部分,但还是成功了。感谢您对的帮助