Skip to content

Instantly share code, notes, and snippets.

@mef
Forked from jczaplew/README.md
Last active August 29, 2015 14:07
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 mef/566bc47c8939f69fda4f to your computer and use it in GitHub Desktop.
Save mef/566bc47c8939f69fda4f to your computer and use it in GitHub Desktop.

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 width = 1100;
var svg = d3.select("#container")
.append("svg")
.attr("preserveAspectRatio","xMinYMin")
.attr("width", width)
.attr("height", width*0.618)
.attr("viewBox", "0 0 " + width + " " + (width*0.618));
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("svg").transition().attr("height", $("#container").width()*0.618).attr("width", $("#container").width());
}
</script>
</body>
</html>
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment