In response to a stack overflow question on how to load a topojson file based on a file input.
Click the map to change the source file.
As topojson files often have a filename (without extenstion) that is equal to the name of the property that holds the features, we can use:
d3.json(fileName + ".json", function(error, topo) { ....
... .data(topojson.feature(topo, topo.objects[fileName]).features)
To ensure that these two match, you can check the topojson itself. Though it can be a pain to find. If you can find the word "objects", you can find the property name.
xxxxxxxxxx
<meta charset="utf-8">
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<svg width="960" height="960"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-geo-projection.v1.min.js"></script>
<script src="https://d3js.org/topojson.v1.min.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var projection = d3.geoMercator()
.scale(170)
.translate([width / 2, height / 2]);
var path = d3.geoPath()
.projection(projection);
var g = svg.append("g");
// Toggle layers based on click.
d3.select("svg").on("click",toggle);
////////// Alternate between the two layers
var detailed = false;
function toggle() {
var source;
g.selectAll("path").remove();
detailed = !detailed;
if (detailed) {
source = "countries";
}
else {
source = "countries2";
}
d3.json(source + ".json", function(error, world) {
var paths = g.selectAll("path")
.data(topojson.feature(world, world.objects[source]).features)
.enter().append("path")
.attr("d", path)
});
}
toggle();
</script>
https://d3js.org/d3.v4.min.js
https://d3js.org/d3-geo-projection.v1.min.js
https://d3js.org/topojson.v1.min.js