Skip to content

Instantly share code, notes, and snippets.

@Andrew-Reid
Last active March 17, 2017 02:31
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/18c99da4ea475797738b6c7e62fb1639 to your computer and use it in GitHub Desktop.
Save Andrew-Reid/18c99da4ea475797738b6c7e62fb1639 to your computer and use it in GitHub Desktop.
Toggle topojson Layers (reload file)

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.

Alternative Apprach

Original Question

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");
// 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment