block by HarryStevens 3bc69a5dd80b7a634b3090c54df36da9

Basic Map Zooming

Full Screen

It’s ridiculous how easy d3-zoom makes it to zoom elements.

index.html

<!DOCTYPE html>
<html>
<head>
  <style>
  body {
    margin: 0;
    font-family: "Helvetica Neue", sans-serif;
    cursor: default;
  }

  .subunit {
    stroke: #fff;
    stroke-width: .5px;
  }
  .subunit.highlight {
    stroke: #000;
    stroke-width: 2px;
  }
  .subunit-boundary {
    fill: none;
    stroke: #000;
    stroke-width: 1px;
  }
  </style>
</head>
<body>
  <script src="https://d3js.org/d3.v4.min.js"></script>
  <!-- <script src="https://d3js.org/d3-geo-projection.v2.min.js"></script> -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/topojson/1.6.20/topojson.min.js"></script>
  <script>
  var width = window.innerWidth, height = window.innerHeight;

  var projection = d3.geoAzimuthalEqualArea()
    .rotate([-70, -10, -1]);

  var path = d3.geoPath()
      .projection(projection)
      .pointRadius(2);

  var svg = d3.select("body").append("svg").attr("width", width).attr("height", height);
  var g = svg.append("g").attr("width", width).attr("height", height);

  var colors = ["#8dd3c7", "#ffffb3", "#bebada", "#fb8072", "#80b1d3", "#fdb462", "#b3de69", "#fccde5", "#fbb4ae", "#b3cde3", "#ccebc5", "#decbe4", "#fed9a6", "#ffffcc", "#e5d8bd", "#fddaec", "#e41a1c", "#377eb8", "#4daf4a", "#984ea3", "#ff7f00", "#ffff33", "#a65628", "#f781bf"];

  d3.json("india_state.json", (error, data) => {
    var feature = topojson.feature(data, data.objects.polygons);

    projection.fitSize([width, height], feature);
    
    g.selectAll(".subunit")
        .data(feature.features, d => d.properties.ST_NM)
      .enter().append("path")
        .attr("class", "subunit")
        .attr("d", path)
        .style("fill", (d, i) => colors[i % colors.length])
        .on("mouseover", function(){
          d3.select(this).classed("highlight", true).raise();
          d3.select(".subunit-boundary").raise();
        })
        .on("mouseout", () => {
          d3.selectAll(".subunit").classed("highlight", false);
        });    

    g.append("path")
        .datum(topojson.mesh(data, data.objects.polygons, (a, b) => a === b))
        .attr("d", path)
        .attr("class", "subunit-boundary");

    var zoom = d3.zoom().scaleExtent([1, 8]).translateExtent([[0, 0], [width, height]]).on("zoom", () => g.attr("transform", d3.event.transform));
    svg.call(zoom);  

    window.onresize = () => {
      width = window.innerWidth, height = window.innerHeight;
      
      svg.attr("width", width).attr("height", height);
      g.attr("width", width).attr("height", height);
      
      projection.fitSize([width, height], topojson.feature(data, data.objects.polygons));
      
      g.selectAll("path").attr("d", path);
      
      zoom.translateExtent([[0, 0], [width, height]]);
      svg.call(zoom);
    }
  });
  </script>
</body>
</html>