gpt4 book ai didi

json - D3 map ,点击并从json中获取id

转载 作者:行者123 更新时间:2023-12-03 05:56:08 25 4
gpt4 key购买 nike

我有 D3 代码,可以根据 JSON 文件中的弧线制作美国 map 。我使用的代码基于此示例 ( 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>

如何单击 map 并返回所单击的州的 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”,其中包含一个字典,其中包含用于制作 map 的弧线以及与此列表中的状态相对应的状态 ID ( https://gist.github.com/mbostock/4090846#file-us-state-names-tsv )。我只是无法找出用于隔离与对象对应的 ID 的正确函数。

最佳答案

首先,您要创建要素网格,这会将所有要素转换为不包含任何数据的多线串。如果您希望在各个状态上发生事件并保留数据,则需要使用 .feature 而不是 .mesh

topojson.mesh:

Returns the GeoJSON MultiLineString geometry object representing the mesh for the specified object in the given topology. This is useful for rendering strokes in complicated objects efficiently, as edges that are shared by multiple features are only stroked once.

https://github.com/mbostock/topojson/wiki/API-Reference#mesh

topojson.特征:

Returns the GeoJSON Feature or FeatureCollection for the specified object in the given topology. If the specified object is a GeometryCollection, a FeatureCollection is returned, and each geometry in the collection is mapped to a Feature. Otherwise, a Feature is returned.

https://github.com/mbostock/topojson/wiki/API-Reference#feature

接下来,您将事件监听器绑定(bind)到 SVG。如果将其绑定(bind)到您正在创建的实际路径,您就可以直接访问数据对象,就像 Lars 在对您的问题的评论中提到的那样:

svg.append("g")
.selectAll("path")
.data(topojson.feature(us, us.objects.states).features)
.enter().append("path")
.attr("class", "state-boundary")
.attr("d", path)
.style("fill", "red")
.on('mousedown.log', function (d) {
console.log(d.id);
});

如果您想绑定(bind)到 SVG 并访问数据,您可以这样做,但我不推荐这样做,只是为了表明这是可能的:

d3.select("svg").on("mousedown.log", function() {
console.log(d3.event.srcElement.__data__.id);
});

关于json - D3 map ,点击并从json中获取id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33987667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com