Skip to content

Instantly share code, notes, and snippets.

@clhenrick
Last active July 21, 2017 21:02
Show Gist options
  • Save clhenrick/6acc95f1a9601d44c3ff3f30cfbe3c7b to your computer and use it in GitHub Desktop.
Save clhenrick/6acc95f1a9601d44c3ff3f30cfbe3c7b to your computer and use it in GitHub Desktop.
Resize Map on Window Resize
license: mit

Using an unprojected version of the us-10m.json so that the Albers USA projection may be applied and that d3-geo's projection.fitSize can be used to appropriately scale the rendering of the data to a small SVG container.

It looks smoother to just rescale the SVG on window resize, but this method could be useful if you were doing other things on the map as well.

Thanks to @veltman for the tip.

Built with blockbuilder.org

forked from clhenrick's block: Debugging d3-geo projection.fitSize

forked from clhenrick's block: Debugging d3-geo projection.fitSize II

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
.chart {
margin: 10px;
}
</style>
</head>
<body>
<svg></svg>
<script>
var svg = d3.select('svg'),
width = window.innerWidth,
height = window.innerHeight;
var states;
function draw() {
// projection fn so we can fit geodata within svg's area
var projection = d3.geoAlbersUsa().fitSize([width, height], states);
// use projection fn with geoPath fn
var path = d3.geoPath().projection(projection);
var g = d3.select('svg g');
if (g) g.remove();
svg.attr('width', width)
.attr('height', height);
svg.append("g")
.attr("class", "states")
.selectAll("path")
.data(states.features)
.enter().append("path")
.attr("d", path)
.attr('fill', '#fff')
.attr('stroke', '#333');
}
d3.json('us-10m-unprojected.topojson', function(error, us) {
if (error) throw error;
// convert our topojson to geojson
states = topojson.feature(us, us.objects.state);
// initial drawing of the map
draw();
// event listener that redraws when the window size changes
// you would probably want to throttle this in production
window.onresize = function() {
width = window.innerWidth;
height = window.innerHeight;
draw();
};
});
</script>
</body>
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