score:5

Accepted answer

i combined the excellent answer here with your data structures. the key you are missing is the conversion of a google maps projection to one that d3 can use. note, i also rewrote your map path code to use d3 data binding instead of loops. here it is in all it's runnable glory:

<!doctype html>
<html>

<head>
  <script src="https://maps.googleapis.com/maps/api/js"></script>
  <script src="//d3js.org/d3.v3.min.js"></script>
  <script src="//d3js.org/topojson.v1.min.js"></script>

  <style>
    #map {
      height: 400px;
      width: 100%;
    }
  </style>

</head>

<body>
  <div id="map"></div>
  <script>
    var map = new google.maps.map(d3.select("#map").node(), {
      zoom: 8,
      center: new google.maps.latlng(43.469740, 10.946157),
      maptypeid: google.maps.maptypeid.roadmap,
      styles: [{
        "stylers": [{
          "saturation": -75
        }, {
          "lightness": 10
        }]
      }]
    });

    d3.json("https://jsonblob.com/api/1e7c9245-e4b6-11e6-90ab-914a66f2a924", function(error, data) {
      if (error) throw error

      //console.log(data[0].comuni[0].geometry.coordinates);
      var overlay = new google.maps.overlayview();

      overlay.onadd = function() {

        var layer = d3.select(this.getpanes().overlaylayer).append("div")

        overlay.draw = function() {

          layer.select('svg').remove();

          var w = 900;
          var h = 600;

          var color = ['#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00', '#ffff33', '#a65628', '#f781bf', '#999999'];
          var heat_color = d3.scale.linear().domain([0, 1]).range(['#b2df8a', '#ff7f00']).interpolate(d3.interpolatehcl);

          var overlayprojection = this.getprojection();

          // turn the overlay projection into a d3 projection
          var googlemapprojection = function(coordinates) {
            var googlecoordinates = new google.maps.latlng(coordinates[1], coordinates[0]);
            var pixelcoordinates = overlayprojection.fromlatlngtodivpixel(googlecoordinates);
            return [pixelcoordinates.x, pixelcoordinates.y];
          }

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

          var svg = layer.append("svg")
            .attr('width', w)
            .attr('height', h)

          var g = svg.selectall("g")
            .data(data)
            .enter()
            .append("g");

          g.selectall("path")
            .data(function(d) {
              return d.comuni;
            })
            .enter()
            .append("path")
            .attr("d", path)
            .attr('class', 'state selected')
            .style("fill", function(d, i) {
              return color[i % color.length];
            })
            .style('opacity', .7);

        }
      }
      overlay.setmap(map);

    });
  </script>
</body>

</html>


Related Query