【发布时间】:2015-11-29 20:26:34
【问题描述】:
我有 D3 代码可以根据 JSON 文件中的弧线制作美国地图。我使用的代码基于此示例 (http://bl.ocks.org/mbostock/4108203),其中这是 json 文件 (http://bl.ocks.org/mbostock/raw/4090846/us.json)
<!DOCTYPE html>
<meta charset="utf-8">
<style>
path {
fill: none;
stroke: #000;
stroke-width: .5px;
}
.land-boundary {
stroke-width: 1px;
}
.county-boundary {
stroke: #aaa;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>
<script>
var width = 960,
height = 500;
var path = d3.geo.path();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.json("js/us.json", function(error, topology) {
if (error) throw error;
svg.append("path")
.datum(topojson.feature(topology, topology.objects.land))
.attr("d", path)
.attr("class", "land-boundary");
svg.append("path")
.datum(topojson.mesh(topology, topology.objects.states, function(a, b) { return a !== b; }))
.attr("d", path)
.attr("class", "state-boundary");
});
</script>
如何点击地图并返回被点击的州的 ID?
第一个console.log现在给我我点击的像素坐标,第二个给我一个svg对象,然后select给我一个父节点..?
d3.select("svg").on("mousedown.log", function() {
console.log(d3.mouse(this));
console.log(this);
console.log(d3.select("id")[0]);
});
json 看起来像它有一个带有字典的对象“states”,其中包括用于制作地图的弧以及与此列表中的状态相对应的状态 ID (https://gist.github.com/mbostock/4090846#file-us-state-names-tsv)。我只是想不出正确的函数来隔离对象对应的 ID。
【问题讨论】:
-
应该是
.on("mousedown.log", function(d) { console.log(d.id); })。