0

我试图让这个例子工作(http://bl.ocks.org/mbostock/2206340)但得到一个错误(下)。我尝试运行的代码与链接中的代码完全相同,但有一个例外,必须修改 json 位置,因为我没有在本地提供 json 文件。

我也一直在尝试几个 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>
4

1 回答 1

1

如果您在 localhost 上运行代码,并以您发布的方式引用它,那么您将收到“Access-Control-Allow-Origin”错误。

如果您将代码放在某个要点上,它将正常工作。

于 2013-07-25T17:28:16.580 回答