Skip to content

Instantly share code, notes, and snippets.

@jczaplew
Last active September 14, 2017 23:21
Show Gist options
  • Save jczaplew/4444770 to your computer and use it in GitHub Desktop.
Save jczaplew/4444770 to your computer and use it in GitHub Desktop.
Responsive TopoJSON Sizing with d3.js

States will adjust in size relative to the width of the container div, which allows SVG elements to be appropriately sized regardless of device size or screen resolution, making it a good way to integrate D3 and Bootstrap.

Click "Open in a new window", change the size of your browser window, and the states will scale with it. *Will not work in the standard bl.ocks.org view

Please let me know if there is a better/native way to do this!

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v0.min.js"></script>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js'></script>
<style type="text/css">
.states {
fill: #aaa;
stroke: #fff;
stroke-width: 0.75px;
}
#container {
margin:2%;
padding:20px;
border:2px solid #d0d0d0;
border-radius: 5px;
}
</style>
</head>
<body onload="sizeChange()">
<div id="container"></div>
<script type="text/javascript">
d3.select(window)
.on("resize", sizeChange);
var projection = d3.geo.albersUsa()
.scale(1100);
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("#container")
.append("svg")
.attr("width", "100%")
.append("g");
d3.json("us-states.json", function(error, us) {
svg.selectAll(".states")
.data(topojson.object(us, us.objects.states).geometries)
.enter().append("path")
.attr("class", "states")
.attr("d", path);
});
function sizeChange() {
d3.select("g").attr("transform", "scale(" + $("#container").width()/900 + ")");
$("svg").height($("#container").width()*0.618);
}
</script>
</body>
</html>
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment