Skip to content

Instantly share code, notes, and snippets.

@larsenmtl
Created February 5, 2017 14:12
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 larsenmtl/879f06e0aaf8591f3408e0faad086db2 to your computer and use it in GitHub Desktop.
Save larsenmtl/879f06e0aaf8591f3408e0faad086db2 to your computer and use it in GitHub Desktop.
fitSize in d3 version 4
license: mit

Dynamically fitting a d3 topojson map to a resizeable container. This uses the new convience method fitSize in d3 version 4.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>jQuery UI Resizable - Default functionality</title>
<script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
<script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/topojson.v2.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<style>
#resizable {
width: 150px;
height: 150px;
padding: 0.5em;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function() {
$("#resizable").resizable({
resize: function(event, ui) {
drawMap(ui.size.width, ui.size.height);
}
});
var svg = d3.select("#resizable")
.append("svg"),
path = svg.append("path");
var states;
d3.json('https://jsonblob.com/api/9e44a352-eb09-11e6-90ab-059f7355ffbc', function(error, data) {
states = topojson.feature(data, data.objects.states);
drawMap(150, 150);
});
function drawMap(w, h) {
svg.attr('width', w)
.attr('height', h);
var projection = d3.geoAlbersUsa()
.scale(1).fitSize([w, h], states);
var geoPath = d3.geoPath().projection(projection);
path
.datum(states)
.attr("d", geoPath);
}
});
</script>
</head>
<body>
<div id="resizable" class="ui-widget-content"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment