javascript - 在 D3 中加载 JSON 给出 null 值

标签 javascript json d3.js

我正在使用 D3 渲染美国 map 。但是,当我尝试加载 JSON 文件时,我收到以下错误消息:

Uncaught TypeError: Cannot read property 'features' of null

这是我正在使用的 JSON 文件:https://github.com/alignedleft/d3-book/blob/master/chapter_12/us-states.json

它与我的所有其他文件位于同一目录中。

// determine width and height
var w = 500;
var h = 300;

// define map projection
var projection = d3.geoAlbersUsa();

// this translates geojson coordinates to svg path codes
var path = d3.geoPath()
             .projection(projection);

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

// load in the geojson file
d3.json("states.json", function(json) {
        console.log(json); // <---- comes up as "null"
        // create one path per geojson feature
        svg.selectAll("path")
           .data(json.features) // <---- THIS is where the error is apparently coming from
           .enter()
           .append("path")
           .attr("d", path);
});

任何见解将不胜感激。谢谢!

最佳答案

匿名函数中的第一个参数是“error”。就像

d3.json(filePath, function(err,data){
if(err) console.log("error fetching data");
// data holds the file content
}); 

可能你错过了。检查https://github.com/d3/d3-request/blob/master/README.md#json

关于javascript - 在 D3 中加载 JSON 给出 null 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38443876/

相关文章:

javascript - 使用 AnalyserNode 进行频率截止

javascript - 在 javascript 中,如何在控制总金额的同时向用户的余额添加随机金额?

javascript - Div 标签背景颜色 CSS HTML

javascript - 在 D3JS 中显示线性和对数刻度之间的动画转换的示例?

javascript - 删除重绘的 d3 svg 元素

d3.js - 字体大小在我的 d3.js 代码中不起作用

javascript - 如何更改标记的颜色

json - 原子编辑器: How do I change toggle-line-comment in the keymap?

json - 需要帮助在 SWIFT 中解析 wikipedia json api

javascript - 如何从加载的 JSON 文件构建外部事件列表?