Skip to content

Instantly share code, notes, and snippets.

@arm5077

arm5077/app.js

Created Aug 31, 2016
Embed
What would you like to do?
Template for resizable D3 v4 map
d3.json("topojson/states.topojson", function(states){
// Make SVG container
var map = d3.select("#map");
var svg = map.append("svg");
var country = svg.append("g");
// Grab width of containing element
var width = d3.select("#map").node().offsetWidth;
// Size container to correct dimensions
map.style("width", width + "px");
map.style('height', width * (600/960) + "px");
// Append country container that we'll stuff outlines into and such
var country = svg.append("g")
.attr("class", "country");
// Apply Albers projection
var projection = d3.geoAlbersUsa()
var path = d3.geoPath()
.projection(projection);
// Draw states
var state = country.selectAll(".state")
.data(topojson.feature(states, states.objects['states']).features)
.enter().append("path")
.attr("d", path)
// Shift map over so it fills the screen better
country.attr("transform", "translate(-" + (width * .1) + ",0), scale(" + width / 800 + ")")
});
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- D3.js -->
<script src="bower_components/d3/d3.min.js"></script>
<!-- TopoJSON -->
<script src="bower_components/topojson/topojson.min.js"></script>
<!-- Page-specific styles -->
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div id="map"></div>
</body>
<!-- My scripts -->
<script src="app.js"></script>
</html>
#map {
width: 900px;
height: 500px;
}
#map svg {
width: 100%;
height: 100%;
}
svg g {
width: 100%;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment