我试图让这个例子工作(http://bl.ocks.org/mbostock/2206340),但得到一个错误(下面)。我试图运行的代码与链接上有一个例外的代码完全相同,必须修改json位置,因为我没有在本地提供json文件。D3.js工作缩放/平移示例?
我一直在尝试几个topojson的例子,以及获取这些错误。我不确定它是一个API版本问题还是什么。任何想法如何得到这个工作,或有人可以启发我如何调试这个问题?我对D3很新。添加错误
GET http://bl.ocks.org/mbostock/raw/4090846/us.json
200 OK
1.29s
d3.v3.min.js (line 1)
TypeError: us is undefined
[Break On This Error]
.data(topojson.feature(us, us.objects.states).features)
更新:
更新代码添加
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.background {
fill: none;
pointer-events: all;
}
#states {
fill: #aaa;
}
#state-borders {
fill: none;
stroke: #fff;
stroke-width: 1.5px;
stroke-linejoin: round;
stroke-linecap: round;
pointer-events: none;
}
</style>
<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 projection = d3.geo.albersUsa()
.scale(1070)
.translate([width/2, height/2]);
var path = d3.geo.path()
.projection(projection);
var zoom = d3.behavior.zoom()
.translate(projection.translate())
.scale(projection.scale())
.scaleExtent([height, 8 * height])
.on("zoom", zoomed);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var g = svg.append("g")
.call(zoom);
g.append("rect")
.attr("class", "background")
.attr("width", width)
.attr("height", height);
d3.json("http://bl.ocks.org/mbostock/raw/4090846/us.json", function(error, us) {
g.append("g")
.attr("id", "states")
.selectAll("path")
.data(topojson.feature(us, us.objects.states).features)
.enter().append("path")
.attr("d", path)
.on("click", clicked);
g.append("path")
.datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
.attr("id", "state-borders")
.attr("d", path);
});
function clicked(d) {
var centroid = path.centroid(d),
translate = projection.translate();
projection.translate([
translate[0] - centroid[0] + width/2,
translate[1] - centroid[1] + height/2
]);
zoom.translate(projection.translate());
g.selectAll("path").transition()
.duration(700)
.attr("d", path);
}
function zoomed() {
projection.translate(d3.event.translate).scale(d3.event.scale);
g.selectAll("path").attr("d", path);
}
</script>
这个错误基本上告诉你,JSON文件不存在。 –
@LarsKotthoff存在http://bl.ocks.org/mbostock/raw/4090846/us.json。 – Wex
您使用的是正确版本的d3吗?如果你不发布一些代码,这将很难帮助你。 – Wex