Skip to content

Instantly share code, notes, and snippets.

@Andrew-Reid
Last active March 17, 2017 02:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Andrew-Reid/0cc5dfb9eedba7afd6712303fb983533 to your computer and use it in GitHub Desktop.
Save Andrew-Reid/0cc5dfb9eedba7afd6712303fb983533 to your computer and use it in GitHub Desktop.
Toggle topojson layers (change visibility)

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.

Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
<!DOCTYPE html>
<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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment