javascript - D3 : Having trouble selecting a path from json data

标签 javascript json d3.js path

尽管阅读了其他人就此事发布的大量问题和答案,但我在将 id 分配给外部坐标 json 文件中的路径时遇到了问题。文件中的数据如下所示(它也在我的 html header 中引用,见下文):

var neighborhoods_json = {
"type": "FeatureCollection",                                                                                
"features": [
{ "type": "Feature", "properties": { "Name": "Roslindale", "density": 5.5800 }, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ -71.1259, 42.2720 ], [ -71.1257, 42.2723 ], [ -71.1256, 42.2724 ], [ -71.1255, 42.2725 ],....

我看到其他人问过同样的问题,答案是添加此行来为每个路径创建 id:

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

但是我的 json 数据不包含 id,所以我想我应该使用 Name 来代替:

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

然后,我尝试使用 Name 作为 id 选择创建的路径之一。我们的想法是简单地选择其中一条路径,然后将其填充颜色更改为红色。但我要么没有正确分配 id,要么没有正确选择路径。谁能告诉我我做错了什么?

    <script src="http://d3js.org/d3.v3.min.js"></script>
    <script src="http://maptimeboston.github.io/d3-maptime/example3/neighborhoods.js"></script>
</head>
<body>
    <script>
        var width = 700,
            height = 580;

        var svg = d3.select( "body" )
          .append( "svg" )
          .attr( "width", width )
          .attr( "height", height );

        var neighborhoods = svg.append( "g" );

        var albersProjection = d3.geo.albers()
          .scale( 190000 )
          .rotate( [71.057,0] )
          .center( [0, 42.313] )
          .translate( [width/2,height/2] );

        var geoPath = d3.geo.path()
          .projection( albersProjection );

        neighborhoods.selectAll( "path" )
          .data( neighborhoods_json.features )
          .enter()
          .append("path")
            .attr( "d", geoPath)
            .attr("id", function(d) {return d.Name;})
            .attr("fill", "steelblue");

        neighborhoods.select("path#Roslindale")
            .attr("fill", "red");

    </script>

最佳答案

id 函数中,Name 属性嵌套在 properties 属性内

neighborhoods.selectAll( "path" )
          .data( neighborhoods_json.features )
          .enter()
          .append("path")
            .attr( "d", geoPath)
            .attr("id", function(d) {return d.properties.Name;})
            .attr("fill", "steelblue");

Working jsfiddle

关于javascript - D3 : Having trouble selecting a path from json data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38626666/

相关文章:

javascript - iAd Producer-如何在Safari中打开YOUTUBE链接?

javascript - 最好使用 Angular 将非 JSON 文件更改为真正的 JSON 文件

javascript - D3 箭头标记表示目标 - 源流,而不是源 - 目标流

javascript - 如何从 Scala (JVM) 中运行 JavaScript 代码?

javascript - 如何编辑数据表按钮的位置?

javascript - 在没有 Handlebars 的情况下使用 Grunt 和 Assemble(使用 Consolidatejs/Swig)?

ios - APNS 严重警报被视为正常通知

javascript - Angular 简单 JSON 请求

javascript - 使用 d3.group 在 D3 中绘制组线

javascript - D3 节点文本显示在工具提示中