Skip to content

Instantly share code, notes, and snippets.

@danasilver
Last active August 29, 2015 13:57
Show Gist options
  • Save danasilver/9497067 to your computer and use it in GitHub Desktop.
Save danasilver/9497067 to your computer and use it in GitHub Desktop.
U.S. Map

A simple demonstration of TopoJSON and interactivity. Mouseover to show the state's abbreviation and the latitude and longitude of the point.

In addition to D3, this visualization relies on TopoJSON. The map uses an Albers USA projection, for which Alaska is scaled by 0.35x, giving it a lie factor of 3. On mousemoves, the corresponding state abbreviation in the data is shown, and the latitude and longitude is computed by inverting the mouse position.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 14px sans-serif;
}
.state {
fill: lightgrey;
stroke: white;
stroke-width: 1px;
transition: fill .1s linear;
}
.state:hover {
fill: coral;
transition: fill .1s linear;
}
.overlay {
fill: none;
}
.focus text {
fill: black;
font-weight: 600;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script>
var width = 960,
height = 500;
var projection = d3.geo.albersUsa()
.scale(1000)
.translate([width / 2, height / 2]);
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.json("us2.json", function(error, us) {
svg.selectAll(".state")
.data(topojson.feature(us, us.objects.usStates).features)
.enter()
.append("path")
.attr("class", "state")
.attr("d", path)
.on("mouseover", function() { focus.style("display", null); })
.on("mouseout", function() { focus.style("display", "none"); })
.on("mousemove", function(d) {
var pos = d3.mouse(this),
latlng = projection.invert(pos);
focus.select(".abbr").text(d.properties.STATE_ABBR);
focus.select(".latlng").text("(" + d3.round(latlng[0], 2) + "\u00B0, "
+ d3.round(latlng[1], 2) + "\u00B0)");
focus.attr("transform", "translate(" + pos[0] + "," + pos[1] + ")");
});
var focus = svg.append("g")
.attr("class", "focus")
.style("display", "none");
focus.append("text")
.attr("class", "abbr")
.attr("x", -10)
.attr("y", -30)
.attr("dy", ".35em");
focus.append("text")
.attr("class", "latlng")
.attr("x", -10)
.attr("y", -13)
.attr("dy", ".35em");
});
</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.
@nkelner
Copy link

nkelner commented Mar 12, 2014

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment