I am new to D3 and JSON, so please bear with me. I am trying to learn how to display maps and have followed tutorials and example code to no avail (e.g., http://bl.ocks.org/michellechandra/0b2ce4923dc9b5809922, https://www.tutorialsteacher.com/d3js/loading-data-from-file-in-d3js). I eventually would like to bind data to the map, but I am currently stuck on getting the map file to display. Chrome isn't giving me any errors, it just shows a blank page and an empty console.
I set up my own web server as recommended in Interactive Data Visualization for the Web and have saved my working files in the "www" folder as indicated.
I realize a similar type of question has been asked numerous times on this forum but none of the solutions have worked. I have tried:
- Moving the location of my local map file (out of a subfolder).
- Pointing to the URL of the map file on the server.
Here's what my code currently looks like:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>D3: Applying a projection to SVG paths</title>
<script src="https://d3js.org/d3.v6.min.js"></script>
<script src="https://d3js.org/topojson.v1.min.js"></script>
<style type="text/css">
path {
stroke: white;
stroke-width: 0.5px;
fill: black;
}
</style>
</head>
<body>
//Sample text to see if anything is working.
<script type="text/javascript">
d3.select("body").append("p").text("Making sure this works.");
</script>
//Code minimally adapted from Scott Murray's D3 book.
<script type="text/javascript">
//Width and height
var w = 500;
var h = 300;
//Define map projection
var projection = d3.geoAlbersUsa()
.translate([w/2, h/2]);
//Define path generator
var path = d3.geoPath()
.projection(projection)
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
//Load in GeoJSON data
d3.json("us-states.json", function(error, data) {
if (error) return console.error(error);
console.log(data);
//Bind data and create one path per GeoJSON feature
svg.selectAll(path)
.data(json.features)
.enter()
.append(path)
.attr("d", path)
.style("stroke", "#fff")
.style("stroke-width", "1")
.style("fill", "steelblue");
}
);
</script>
//Sample text to see if anything is working.
<script type="text/javascript">
d3.select("body").append("p").text("And this too.");
</script>
</body>
</html>
Chrome loads the page -- I put sample text in a few places in the code to make sure it was doing something and those appear just fine. However, I asked the data to be logged on the console and nothing is there.
There may be other things wrong with my code, but I suspect this hurdle has something to do with the map file and web server as I can create other svg objects without a problem. Appreciate your support!