I am trying to take the D3 Hexbin example found at https://bl.ocks.org/mbostock/4330486 and scale the map to fit the width of the parent element. I have followed the code found in the answer Center a map in d3 given a geoJSON object, but the map is all messed up (see code snippet below). The goal of this change is to allow the map to be on a responsive webpage.
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var parseDate = d3.timeParse("%x");
var color = d3.scaleTime()
.domain([new Date(1962, 0, 1), new Date(2006, 0, 1)])
.range(["black", "steelblue"])
.interpolate(d3.interpolateLab);
var hexbin = d3.hexbin()
.extent([[0, 0], [width, height]])
.radius(10);
var radius = d3.scaleSqrt()
.domain([0, 12])
.range([0, 10]);
// Per https://github.com/topojson/us-atlas
var projection = d3.geoAlbersUsa()
.scale(1)
.translate([0, 0]);
var path = d3.geoPath().projection(projection);
d3.queue()
.defer(d3.json, "https://d3js.org/us-10m.v1.json")
.await(ready);
function ready(error, us, walmarts) {
if (error) throw error;
var country = topojson.feature(us, us.objects.nation);
var b = path.bounds(country),
s = .95 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0][1]) / height),
t = [(width - s * (b[1][0] + b[0][0])) / 2, (height - s * (b[1][1] + b[0][1])) / 2];
projection
.scale(s)
.translate(t);
svg.append("path")
.datum(country)
.attr("class", "nation")
.attr("d", path);
svg.append("path")
.datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
.attr("class", "states")
.attr("d", path);
}
.nation {
fill: #ddd;
}
.states {
fill: none;
stroke: #fff;
stroke-linejoin: round;
}
.hexagon {
stroke: #fff;
}
<svg width="960" height="600"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-hexbin.v0.2.min.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>