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?