Use this to showcase state-level information by clicking on a state.
Last active
December 11, 2015 00:53
-
-
Save mtaptich/643c16d4a3ff0b231403 to your computer and use it in GitHub Desktop.
Showcase States
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<body> | |
<style> | |
.land { | |
fill: #eee; | |
stroke: #777777; | |
} | |
.title { | |
font-family: "Lato", "PT Serif", serif; | |
font-size: 40px; | |
font-weight: 400; | |
-webkit-font-smoothing: antialiased; | |
-webkit-font-smoothing: antialiased; | |
} | |
</style> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<script src="http://d3js.org/topojson.v1.min.js"></script> | |
<script src="http://d3js.org/d3.geo.projection.v0.min.js"></script> | |
<script src="http://d3js.org/queue.v1.min.js"></script> | |
<script> | |
var width = 960, | |
height = 420, | |
clickOn = false; | |
var projection = d3.geo.albersUsa() | |
.scale(800) | |
.translate([700 /2, height / 2.1]); | |
var path = d3.geo.path() | |
.projection(projection); | |
var svg = d3.select("body").append("svg") | |
.attr("width", width) | |
.attr("height", height); | |
svg.append("text") | |
.attr('class', 'title') | |
.attr('x', width/2) | |
.attr('y', 35) | |
.style('text-anchor', 'middle') | |
.text("Trigger a Transition on Click") | |
queue() | |
.defer(d3.json, "http://mtaptich.github.io/d3-lessons/d3-maps/state_pol.json") | |
.await(ready); | |
function ready (error, us) { | |
svg.append("g") | |
.attr("class", "land") | |
.selectAll("path") | |
.data(topojson.feature(us, us.objects.state_pol).features) | |
.enter().append("path") | |
.attr("class", function(d) {return d.id}) | |
.attr("d", path) | |
.on("click", function(){ | |
if(clickOn){ | |
last.style("fill", "#eee"); | |
last.transition().duration(200).attr("transform", "translate(0,0)"); | |
} | |
var state = d3.select(this); | |
var xy = getCentroid(state) | |
state.transition().duration(200) | |
.style('fill', '#fdb03f') | |
.attr("transform", "scale(1.9)translate("+(400-xy[0])+"," + (115-xy[1]) + ")") | |
last = d3.select(this); | |
clickOn = true; | |
}) | |
}; | |
function getCentroid(selection) { | |
// get the DOM element from a D3 selection | |
// you could also use "this" inside .each() | |
var element = selection.node(), | |
// use the native SVG interface to get the bounding box | |
bbox = element.getBBox(); | |
// return the center of the bounding box | |
return [bbox.x + bbox.width/2, bbox.y + bbox.height/2]; | |
} | |
d3.select(self.frameElement).style("height", height + "px"); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment