|
var App = (function () { |
|
"use strict"; |
|
|
|
var App = { |
|
stateCode: window.location.search.substr(1) || 'ma' |
|
}; |
|
|
|
d3.json("us-" + App.stateCode + ".json", ready); |
|
|
|
function ready(error, topo) { |
|
if (error) throw error; |
|
|
|
App.state = topojson.feature(topo, topo.objects.state); |
|
App.counties = topojson.feature(topo, topo.objects.counties).features; |
|
|
|
App.div = d3.select('#app'); |
|
App.size = [ |
|
parseInt(App.div.style('width')), parseInt(App.div.style('height')) |
|
]; |
|
|
|
App.path = d3.geoPath() |
|
.projection(null); |
|
|
|
App.transform = zoomBounds(App.path.bounds(App.state), App.size); |
|
|
|
App.zoom = d3.zoom() |
|
.translateExtent([[0, 0], App.size]) |
|
.scaleExtent([App.transform.k, App.transform.k * 2]) |
|
.on("zoom", zoomed); |
|
|
|
App.svg = App.div.append("svg") |
|
.call(App.zoom); |
|
|
|
App.svg.append("rect") |
|
.classed("background", true) |
|
.on("click", reset); |
|
|
|
App.g = App.svg.append("g") |
|
.attr("transform", App.transform); |
|
|
|
App.g.selectAll("path") |
|
.data(App.counties) |
|
.enter().append("path") |
|
.classed("county", true) |
|
.attr("d", App.path) |
|
.on("click", clicked); |
|
|
|
reset(); |
|
} |
|
|
|
function zoomBounds(bounds, size) { |
|
// Calculate dimensions of bounds |
|
// and scale to fit inside container |
|
var width = bounds[1][0] - bounds[0][0], |
|
height = bounds[1][1] - bounds[0][1], |
|
scale = 1 / Math.max(width / size[0], height / size[1]); |
|
|
|
// Calculate center of bounds |
|
// and difference from center of container |
|
var x = (bounds[0][0] + bounds[1][0]) / 2, |
|
y = (bounds[0][1] + bounds[1][1]) / 2, |
|
translate = [size[0] / 2 - scale * x, size[1] / 2 - scale * y]; |
|
|
|
return d3.zoomIdentity |
|
.translate(translate[0], translate[1]) |
|
.scale(scale); |
|
} |
|
|
|
function zoomed() { |
|
App.g.attr("transform", d3.event.transform); |
|
} |
|
|
|
function reset() { |
|
App.svg.call(App.zoom.transform, App.transform); |
|
} |
|
|
|
function clicked() { |
|
App.svg.select(".active") |
|
.classed("active", false); |
|
|
|
d3.select(this) |
|
.classed("active", true); |
|
} |
|
|
|
return App; |
|
})(); |