block by shimizu 49f963c39c11c64d6c764bc3213b3191

D3 v4 + Google Maps API

Full Screen

Built with blockbuilder.org

index.html


<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
  html, body {
    width: 100%;
    height: 100%;
    padding: 0px;
    margin: 0px;
  }

  #map {
    width: 960px;
    height: 500px;
  }

  .SvgOverlay {
    position: relative;
    width: 960px;
    height: 500px;           
  }

  .SvgOverlay svg {
    position: absolute;
    top: -4000px;
    left: -4000px;
    width: 8000px;
    height: 8000px;        
  }

  .SvgOverlay path {
    stroke: black;
    stroke-width: 1px;
    fill-opacity: .6;
  }
</style>
</head>
<body>
<div id="map"></div>


<script src="//maps.googleapis.com/maps/api/js?sensor=false"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.min.js"></script>    

  
<script>
  d3.json("gunma.geojson", main);

  function main(json) {

    //Google Map 初期化
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 9,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: new google.maps.LatLng(36.53, 139.06),       
    });

    //OverLayオブジェクトの作成
    var overlay = new google.maps.OverlayView(); 
    overlay.onAdd = function () {

      //オーバーレイ設定
      var layer = d3.select(this.getPanes().overlayLayer).append("div").attr("class", "SvgOverlay");
      var svg = layer.append("svg");
      var gunmalayer = svg.append("g").attr("class", "AdminDivisions");
      var markerOverlay = this;
      var overlayProjection = markerOverlay.getProjection();

      //Google Projection作成
      var googleMapProjection = d3.geoTransform({point: function(x, y) {
        d = new google.maps.LatLng(y, x);
        d = overlayProjection.fromLatLngToDivPixel(d);
        this.stream.point(d.x + 4000, d.y + 4000);
      }});
      //パスジェネレーター作成
      var path = d3.geoPath().projection(googleMapProjection); 

      overlay.draw = function () {

        //地図描く
        gunmalayer.selectAll("path")
          .data(json.features)
          .attr("d", path) 
          .enter().append("path")
          .attr("d", path)
          .attr("class", function(d) { return "gunma" + d.id; });

        //色塗り
        var grad = d3.scaleLinear().domain([0, 38]).range(["#0000FF", "#FFFFFF"]);
        for(var i=0; i < 36+1; i++){
          d3.select(".gunma"+i).attr("fill", grad(i));
        }
      };
    };

    //作成したSVGを地図にオーバーレイする
    overlay.setMap(map);

    //せっかくなんでアニメーションとかも付けてみる。
    var anime = Anime();
    setInterval(anime, 1000);

  };
  function Anime(){			
    var flag = true;
    return function(){
      if(flag){
        d3.select(".gunma16").transition().attr("fill", "red");
        flag = false;
      }else{
        d3.select(".gunma16").transition().attr("fill", "blue");
        flag = true;
      }
    }
  }
</script>
</body>
</html>