Alternative approach to toggling layers, compared to : Toggling layers, reload file
Has the advantage of loading data only once, so it should be a smoother transition between toggles.
Click anywhere on the map to toggle layers.
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");
/// Add different layers
d3.json("countries.json", function(error, world) {
var paths = g.selectAll(".complex")
.data(topojson.feature(world, world.objects.countries).features)
.enter().append("path")
.attr("d", path)
.attr("opacity",1) // choose one to show by default
.attr("class", "layer complex");
});
d3.json("countries2.json", function(error, world) {
var paths = g.selectAll(".simple")
.data(topojson.feature(world, world.objects.countries2).features)
.enter().append("path")
.attr("d", path)
.attr("opacity",0) // hide the other
.attr("class", "layer simple");
});
d3.select("svg").on("click",toggle);
/// Alternate between the two.
var detailed = true;
function toggle() {
console.log("toggle");
detailed = !detailed;
console.log(detailed);
g.selectAll(".layer").attr("opacity",0);
if (detailed) {
g.selectAll(".complex").attr("opacity",1);
}
else {
g.selectAll(".simple").attr("opacity",1);
}
}
</script>
https://d3js.org/d3.v4.min.js
https://d3js.org/d3-geo-projection.v1.min.js
https://d3js.org/topojson.v1.min.js