Access svg attributes from index.html in d3.js

Viewed 53

I am trying to replicate this d3.js worldmap:

https://www.d3-graph-gallery.com/graph/backgroundmap_basic.html

However I want to reorganize the code into two parts, index.html and Worldmap.js,

index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8"/>
    <title>Worldmap</title>
    <script src="https://d3js.org/d3.v6.js"></script>
    <script type="text/javascript" src=Worldmap.js></script>

  </head>

  <body>
    <svg id="my_dataviz" width="400" height="300"></svg>
  </body>
</html>

Worldmap.js:


// The svg
var svg = d3.select("svg"),
    width = +svg.attr("width"),
    height = +svg.attr("height");

// Map and projection
var projection = d3.geoNaturalEarth1()
    .scale(width / 1.3 / Math.PI)
    .translate([width / 2, height / 2])

// Load external data and boot
d3.json("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world.geojson",
   function(data){

    // Draw the map
    svg.append("g")
        .selectAll("path")
        .data(data.features)
        .enter().append("path")
            .attr("fill", "#69b3a2")
            .attr("d", d3.geoPath()
                .projection(projection)
            )
            .style("stroke", "#fff")
})

However I get the following error:

Uncaught TypeError: node is null

selection_attr https://d3js.org/d3.v6.js:1835
<anonymous> Worldmap.js:6

What am I doing wrong here? I suppose the d3.js cant select the svg attributes from the index.html?

1 Answers
  1. Use d3.json as a Promise:
const url = "https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world.geojson";
d3.json(url)
  .then(drawMap)
  .catch(err => console.log(err));
  1. Call projection with data:
.attr("d", d => d3.geoPath().projection(projection)(d))

const svg = d3.select("svg");
const width = parseInt(svg.attr("width"));
const height = parseInt(svg.attr("height"));

// Map and projection
var projection = d3.geoNaturalEarth1()
    .scale(width / 1.3 / Math.PI)
    .translate([width / 2, height / 2])

// Load external data and boot

const drawMap = data => {
    // Draw the map
    svg.append("g")
        .selectAll("path")
        .data(data.features)
        .enter()
        .append("path")
            .attr("fill", "#69b3a2")
            .attr("d", d => d3.geoPath()
                .projection(projection)(d))
            .style("stroke", "#fff")
};

const url = "https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world.geojson";
d3.json(url)
    .then(drawMap)
  .catch(err => console.log(err));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.7.0/d3.min.js"></script>

<svg width="500" height="500" />

Related