【问题标题】:D3 map, click and get id from jsonD3映射,点击从json获取id
【发布时间】: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); })

标签: json d3.js svg


【解决方案1】:

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

topojson.mesh:

返回 GeoJSON MultiLineString 几何对象,表示给定拓扑中指定对象的网格。这对于有效地在复杂对象中渲染笔触很有用,因为由多个特征共享的边缘只被描边一次。

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

topojson.feature:

返回给定拓扑中指定对象的 GeoJSON Feature 或 FeatureCollection。如果指定的对象是 GeometryCollection,则返回 FeatureCollection,并将集合中的每个几何图形映射到 Feature。否则,返回一个 Feature。

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

接下来,您将事件监听器绑定到 SVG。如果您将它绑定到您正在创建的实际路径,您就可以直接访问数据对象,就像 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);
        });

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    • 1970-01-01
    • 2021-06-30
    • 2019-09-12
    • 1970-01-01
    相关资源
    最近更新 更多