来自 geojson 的 D3js Select 特性

D3js Select feature from geojson

学习D3,我正在学习很多教程。到目前为止,我可以为所有美国州创建一个带有外部 json 文件的美国地图。但是,我喜欢绘制只有一个州的地图(比如阿拉巴马州,这是 json 文件中的第一个特征)。

目前的代码:

<script>

        var w = 500;
        var h = 300;

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

        var projection = 3.geo.albersUsa().translate([w/2,h/2]).scale([500]);
        var path = d3.geo.path().projection(projection);

        d3.json("us-states.json", function(json){

            svg.selectAll("path")
                .data(json.features)
                .enter()
                .append("path")
                .attr("d",path)
                .style("fill", "teal");
        });

   </script>

以及 .json 的结构:

{"type":"FeatureCollection","features":[{"type":"Feature","id":"01","properties":{"name":"Alabama"},"geometry":
{"type":"Polygon","coordinates":[[[-87.359296,35.00118],[-85.606675,34.984749],[-85.431413,34.124869],[-85.184951,32.859696],...

最原始的方法是手动创建一个新的 json 文件,其中只有阿拉巴马州,但我相信有更好的方法。我想我想用 json object 创建一个新变量,我想随后在 d3.json-function 中使用它。类似于:

var alabama = "us-states.json" (features.id["01"])

d3.json("alabama", function(json){
...

但我不知道如何从 json 主文件中获取信息。

您可以 select 按索引声明并将所有内容放入数组中。像这样:

.data([topojson.feature(us, us.objects.states).features[1]])