block by bycoffe e32cc94b26df9c5e28aa

Town/county switch with topojson

Full Screen

index.html

<!DOCTYPE html>
<meta charset="utf-8">
<style>
  #map path {
    fill: #fff;
    stroke: #999;
    stroke-width; 1;
  }
  #map path.state.border {
    fill: none;
    stroke-width: 2;
    stroke: #333;
  }
  #map path.county.border {
    fill: none;
    stroke-width: 2;
    stroke: #666;
  }
</style>

<body>

  <div id="map"></div>

</body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/topojson/1.6.20/topojson.js"></script>
<script>

  d3.json("nh-towns.json", function(err, topo) {
    var margin = {top: 0, right: 0, bottom: 0, left: 0},
        width = 500,
        height = 590,

        path = d3.geo.path().projection(null),

        svg = d3.select("#map").append("svg").attr({
          width: width + margin.left + margin.right,
          height: height + margin.top + margin.bottom,
        })

        g = svg.append("g").attr({
          transform: "translate(" + margin.left + "," + margin.top + ")scale(.83)"
        }),

        town = g.selectAll("path.town")
                  .data(topojson.feature(topo, topo.objects.counties).features)
                .enter().append("path")
                  .attr({
                    "class": "town border",
                    d: path
                  })
                  .style({
                    opacity: 1
                  }),

        countyBorder = g.append("path")
                          .datum(topojson.mesh(topo, topo.objects.counties, function(a, b) {
                            return String("000" + a.properties.fips).slice(-6).slice(0, 3) !== String("000" + b.properties.fips).slice(-6).slice(0, 3);
                          }))
                          .attr({
                            "class": "county border",
                            d: path
                          })
                          .style({
                            opacity: 0
                          })

        stateBorder = g.append("path")
                          .datum(topojson.mesh(topo, topo.objects.counties, function(a, b) {
                            return a === b;
                          }))
                          .attr({
                            "class": "state border",
                            d: path
                          });

    var selected = "town";

    function toggle() {
      town.transition()
              .duration(1000)
              .style({
                opacity: selected === "town" ? .1 : 1
              });

      countyBorder.transition()
              .duration(1000)
              .style({
                opacity: selected === "town" ? 1 : .1 
              });

      selected = selected === "town" ? "county" : "town";
      window.setTimeout(toggle, 1500);
    }

    toggle();

  });


</script>