d3.js choropleth映射示例错误
我正在尝试使用d3.js提供的一个示例来学习构建choropleth映射 当我从示例中的.tsv文件切换到版本中的.json文件时,我不断收到一个错误:“TypeError:congress.forEach不是一个函数”。以下是我正在使用的代码:d3.js choropleth映射示例错误,d3.js,D3.js,我正在尝试使用d3.js提供的一个示例来学习构建choropleth映射 当我从示例中的.tsv文件切换到版本中的.json文件时,我不断收到一个错误:“TypeError:congress.forEach不是一个函数”。以下是我正在使用的代码: <script type="text/javascript"> var width = 960, height = 500; var path = d3.geo.path(); var svg = d3.sele
<script type="text/javascript">
var width = 960,
height = 500;
var path = d3.geo.path();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var g = svg.append("g")
.call(d3.behavior.zoom()
.scaleExtent([1, 10])
.on("zoom", zoom));
d3.json("us-10m.json", function (error, us) {
d3.json("https://www.govtrack.us/api/v2/role?current=true", function (error, congress) {
var memberId = {};
congress.forEach(function (d) { //TypeError:congress.forEach is not a function
memberId[d.id] = +d.id;
});
g.append("g")
.attr("class", "states")
.selectAll("path")
.data(topojson.feature(us, us.objects.states).features)
.enter().append("path")
.attr("d", path)
.style("fill", function (d) {
return color(memberId[d.id]); // <-C
});
g.append("path")
.datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
.attr("class", "states")
.attr("d", path);
});
});
function zoom() {
g.attr("transform", "translate("
+ d3.event.translate
+ ")scale(" + d3.event.scale + ")");
}
可变宽度=960,
高度=500;
var path=d3.geo.path();
var svg=d3.选择(“正文”).追加(“svg”)
.attr(“宽度”,宽度)
.attr(“高度”,高度);
var g=svg.append(“g”)
.call(d3.behavior.zoom()
.scaleExtent([1,10])
。打开(“缩放”,缩放));
d3.json(“us-10m.json”),函数(错误,us){
d3.json(“https://www.govtrack.us/api/v2/role?current=true,函数(错误,会议){
var memberId={};
congress.forEach(函数(d){//TypeError:congress.forEach不是函数
memberId[d.id]=+d.id;
});
g、 附加(“g”)
.attr(“类别”、“状态”)
.selectAll(“路径”)
.data(topojson.feature(us,us.objects.states).features)
.enter().append(“路径”)
.attr(“d”,路径)
.样式(“填充”,功能(d){
返回颜色(memberId[d.id]);//congress
不是数组-它是一个对象:
{
meta: {
limit: 100,
offset: 0,
total_count: 540
},
objects: [ {...}, {...}, {...}, {...} ]
}
需要迭代国会。对象
:
congress.objects.forEach(function() {...})
这在您的计算机上是一个跨域问题,就像在JSFIDLE上一样,这就是为什么
congress
为空(因此forEach
不存在)。您可以将文件复制到项目目录中,以便所有内容都是本地主机。谢谢meetamit。我尝试了您的建议,但仍然收到相同的错误。您是否更改了“https://www.govtrack.us/api/v2/role?current=true“
至”/path/to/local.json”
?当您查看开发工具->网络面板时,会看到什么?我可以在firebug控制台中看到congress.json信息。控制台中的下一行是“TypeError:congress.forEach不是函数”谢谢您,阿米特!观察得很好,错误消失了。