0

I'm having some difficulty getting d3 to render a geoAlbersUsa projection from topoJson data. I'm showing a blank screen, but no errors returned. The geoJson data seems to be coming through fine, but it's not rendering the path for some reason. Any help would be greatly appreciated!

Here's the relevant code:

<!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>
saganaga
  • 63
  • 7

1 Answers1

1

You need to join with an element:

            .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")
SmokeyShakers
  • 3,372
  • 1
  • 7
  • 18
  • Oh yeah, duh! Thanks for that... kind of obvious. This did produce another problem however. It is rendering the SVG, however it is showing a mangled mess of intersecting lines (nothing resembling a U.S. map to be sure!). Here is an example I found of a similar problem, https://stackoverflow.com/questions/33216839/random-lines-when-loading-a-topojson-file-in-d3. Unfortunately the solution is not applicable in my case. Any ideas on why this might be occuring? – saganaga Apr 29 '21 at 15:20
  • 1
    @saganaga, your data is already projected but you are projecting it as though it weren't. Try a null projection, d3.geoIdentity, or finding an unprojected data set. See [here](https://stackoverflow.com/q/42430361/7106086) – Andrew Reid Apr 29 '21 at 15:52
  • Perfect Andrew! I simply changed d3.geoPath(projection) to d3.geoPath(null) and it's now displaying correctly. Thanks! – saganaga Apr 29 '21 at 16:01