为什么我无法使用 topojson 获得要渲染的 d3.js 地图?

时间:2021-04-29 14:18:47

标签: d3.js topojson

我在使用 d3 从 topoJson 数据渲染 geoAlbersUsa 投影时遇到了一些困难。我显示一个空白屏幕,但没有返回任何错误。 geoJson 数据似乎很好,但由于某种原因它没有渲染路径。任何帮助将不胜感激!

相关代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="https://d3js.org/d3.v6.min.js"></script>
    <script src="https://unpkg.com/topojson-client@3"></script>
</head>
<body>
    <script>
        const width = 1000;
        const height = 600;

        const projection = d3.geoAlbersUsa()
            .translate([width / 2, height / 2])
            .scale(800);

        const path = d3.geoPath(projection);

        const svg = d3.select("body")
            .append("svg")
            .attr("height", height)
            .attr("width", width)
            .style("display", "block")
            .style("margin", "auto");

        d3.json("https://d3js.org/us-10m.v1.json").then(data => {
            svg.selectAll(".states")
                .data(topojson.feature(data, data.objects.states).features)
                .attr("d", path)
                .style("fill", "none")
                .attr("class", "states")
                .style("stroke", "black")
                .style("stroke-width", "2px")
        });
    </script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

你需要加入一个元素:

            .data(topojson.feature(data, data.objects.states).features)
            .join("path") // here
            .attr("d", path)
            .style("fill", "none")
            .attr("class", "states")
            .style("stroke", "black")
            .style("stroke-width", "2px")
相关问题