D3:从json数据中选择路径时遇到问题

时间:2016-07-28 03:35:53

标签: javascript json d3.js path

我无法从外部json坐标文件中为路径分配ID,尽管他阅读了其他人在此问题上发布的大量问题和答案。文件中的数据看起来像这样(它也在我的html的标题中引用,见下文):

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>

1 个答案:

答案 0 :(得分:2)

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