【问题标题】:google maps with d3 paths as a layer using (d3 v4)使用 d3 路径作为图层的谷歌地图(d3 v4)
【发布时间】:2017-04-03 23:51:48
【问题描述】:

我有以下代码,它采用谷歌地图,然后在其上附加一个图层,但投影中有一个问题,这给了我一个错误,并且不单独在谷歌地图上显示图层,任何帮助都会受到赞赏。 请注意,我使用的是 d3 的第 4 版。 有什么建议吗?

<script>
    var map = new google.maps.Map(d3.select("#map").node(), {
      zoom: 7,
      center: new google.maps.LatLng(31.5852,36.2384),
      mapTypeId: google.maps.MapTypeId.ROADMAP });

 d3.json("Export.json", function(error, jordanLevel2) {
      if (error) throw error
      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 = 900;


          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.geoPath().projection(googleMapProjection);


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

          var g = svg.append('g')
            .attr("id", "mapGroup");


          g.selectAll("path")
            .data(jordanLevel2.features)
            .enter()
            .append("path")
            .attr("d", path)
            .attr('class', 'state selected')

            .style('opacity', .7);

        }
      }
      overlay.setMap(map);

    });

【问题讨论】:

    标签: javascript d3.js


    【解决方案1】:

    解决方案

    如果您的上述代码适用于 D3 v3,您需要做的是将 googleMapProjection 函数替换为以下 d3.geoTransform 函数:

    transform = d3.geoTransform({point: function(x, y) {
                      d = new google.maps.LatLng(y, x);
                      d = overlayProjection.fromLatLngToDivPixel(d);
                      this.stream.point(d.x, d.y);
                    }
                  });
    

    然后,将path 变量替换为:

    var path = d3.geoPath().projection(transform);
    

    说明

    我想您已经知道 Mike Bostock 在回答某个相关问题时解释了 here 在 v4 中所做的更改。具体来说,由于这是一个平面变换(因为我们将纬度/经度坐标转换为像素),我们需要使用d3.geoTransform()

    在 v3 和 v4 中,我们采用了一个函数,其中输入应该是您试图在谷歌地图上绘制的覆盖形状轮廓的纬度/经度坐标*。然后该函数像以前一样使用fromLatLngToDivPixel 方法将这些值转换为svg 叠加层中的像素位置,然后projection.stream 方法将这些值传递回路径对象,然后在绘制叠加层时调用该对象。

    据我所知,这里 v3 和 v4 的区别是:

    1. 您不能使用回退投影,因此必须改用projection.stream 方法。
    2. 替换googleMapProjection 函数transform 单独获取x 和y 坐标,而不是在单个数组中一起获取。

    *或相对坐标,例如与 topojson

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-07
      相关资源
      最近更新 更多