block by syntagmatic 3754100

Centering on a region

Full Screen

A demonstration of centering on a region using d3.geo.azimuthal.invert()

113th US Congressional Voting Districts provided by Len De Groot

index.html

<!DOCTYPE html>
<meta charset="utf-8">
<title>Centering on a region</title>
<style>
svg {
  background: #a4bac7;
}
path.district {
  fill: #d7c7ad;
  stroke: #766951;
  stroke-width: 1px;
}
path:hover {
  fill: #8d7f67;
}
text {
  font-size: 24px;
}
</style>
<svg width="960" height="500"></svg>
<p>
Click to center on a district.<br/>
<a href="#" id="zoom-out">Reset Zoom</a>
</p>
<script src="//d3js.org/d3.v2.js"></script>
<script>
var districts = [
  "AK00",
  "AL05",
  "AZ06",
  "CA12",
  "CO04",
  "FL02",
  "IA04",
  "ME02",
  "MN03",
  "TX23",
  "VT00",
  "WA04"
];

var svg = d3.select("svg");

var projection = d3.geo.azimuthal()
    .mode("equidistant")
    .origin([-88, 48])
    .scale(400)
    .translate([480, 260]);

var path = d3.geo.path()
  .projection(projection);

d3.json("113-cong.json", function(collection) {
  // visible districts
  var selected = collection.features.filter(function(district) {
    return districts.indexOf(district.properties.UID) > -1;
  });

  svg.selectAll("path.district")
      .data(selected)
    .enter().append("path")
      .attr("class", "district")
      .attr("d", path)
      .on("mouseover", function(d) {
        svg.select("#district").text(d.properties.UID);
      })
      .on("click", function(d) {
        var origin = path.centroid(d);
        var bounds = d3.geo.bounds(d);
        var bound_height = bounds[1][1]-bounds[0][1];
        projection.origin(projection.invert(origin)).scale(8000/bound_height);
        svg.selectAll("path.district").transition().duration(1000).attr("d", path);
      });

  svg.append("text")
    .attr({
      "id": "district",
      "x": 220,
      "y": 420,
    });
});

d3.select("#zoom-out").on("click", function() {
  projection
    .origin([-88, 48])
    .scale(400);
  svg.selectAll("path.district").transition().duration(1000).attr("d", path);
});
</script>