【问题标题】:d3 how to add ID from geojson to pathd3如何将geojson中的ID添加到路径
【发布时间】:2014-05-24 00:22:31
【问题描述】:

我有以下代表印度每个州的 geojson 文件,作为一个简单的示例,一个声明看起来像这样(为简洁起见,删除了坐标):

    {
"type": "FeatureCollection",
"features": [
{ "type": "Feature", "properties": {}, "id":"AndhraPradesh", "geometry": { "type": "MultiPolygon", "coordinates": [ ......

我试图让生成的 SVG 的路径具有其 geojson 形状的 id,这样我就会有类似的东西:

<svg width="600" height="600"><g id="india"><path id="AndhraPradesh" d="..."></path>

以下内容及其变体似乎不起作用,并且我找不到将路径与 id 明确关联的示例,因此我不确定秘密可能是什么。

  var w = 600;
  var h = 600;
  var proj = d3.geo.mercator();
  var path = d3.geo.path().projection(proj);
  var t = proj.translate(); // the projection's default translation
  var s = proj.scale() // the projection's default scale

  var map = d3.select("body").append("svg")
      .attr("width", w)
      .attr("height", h)
      .call(initialize);

  var india = map.append("g")
      .attr("id", "india");

  d3.json("india_states.geojson", function (json) {
    india.selectAll("path")
      .data(json.features)
      .enter().append("path")
      .attr("d", path)
      .attr("id", id)
  });

非常感谢任何帮助。

【问题讨论】:

    标签: javascript svg d3.js


    【解决方案1】:

    这应该可以解决问题:

       .attr("id", function(d) { return d.id; })
    

    它返回与路径关联的数据的id字段。

    【讨论】:

    • 谢谢,这样干净多了。我刚刚发现 console.log(india[0][0].children[i].__data__.id) 也可以让我访问它,但这要好得多。
    猜你喜欢
    • 2018-04-23
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 2014-10-20
    • 1970-01-01
    • 2013-03-05
    相关资源
    最近更新 更多