css缩放的谷歌地图点击不正确的坐标

css-scaled google maps click incorrect coordinates

本文关键字:不正确 坐标 谷歌地图 缩放 css      更新时间:2023-09-26

我在一个css缩放的容器中插入了一个Google Maps地图。由于项目的特殊性,这是无法避免的。我需要跟踪这个地图上的点击坐标,但是缩放地图设置了不正确的坐标(参见代码片段)。

如何解决这个问题?我暂时没有主意。

const map = new google.maps.Map(document.querySelector('#map'), {
  center: {lat: 48.7, lng: 31},
  zoom: 6
});
google.maps.event.addListener(map, 'click', (event)=> {
  const marker = new google.maps.Marker({
    position: event.latLng,
    map: map
  });
});
html, body {
    height: 100%;
  }
.container {
  width: 800px;
  height: 600px;
  transform: scale(1.2);
  }
#map {
  width: 100%;
  height: 100%;
  }
<script src="https://maps.googleapis.com/maps/api/js?.js"></script>
<div class="container">
<div id="map"></div>
</div>

好的,找出了如何修正修正(这是当转换中心为0,0时)

function point2LatLng(point, transformScale, map) {
    var topRight = map.getProjection().fromLatLngToPoint(map.getBounds().getNorthEast());
    var bottomLeft = map.getProjection().fromLatLngToPoint(map.getBounds().getSouthWest());
    var scale = Math.pow(2, map.getZoom());
    var worldPoint = new google.maps.Point(point.x / transformScale / scale + bottomLeft.x, point.y / transformScale / scale + topRight.y);
    return map.getProjection().fromPointToLatLng(worldPoint);
  }
gmaps.event.addListener(this.map, 'click', (event)=> {
          let transformMatrix = window.getComputedStyle(this.$el.closest('.container')).transform.match(/^matrix'((.+)')$/)[1].split(', ');
          let transformScale = parseFloat(transformMatrix[0]);
          var marker = new gmaps.Marker({
              position: point2LatLng(event.pixel, transformScale, this.map),
              map: this.map
          });
        });

这个答案可以工作,但是缩放地图的工作非常糟糕,许多与坐标相关的功能不能正确工作。但是有一个解决方法:将映射放在虚拟iframe中:

    const iframe = this.$el.querySelector('iframe');
    iframe.contentWindow.document.open();
    iframe.contentWindow.document.write('<div id="map" style="width: 100%; height: 100%"></div>');
    iframe.contentWindow.document.close();
    const mapContainer = iframe.contentWindow.document.querySelector('#map');
    const map = new gmaps.Map(mapContainer, {
              center: {lat: 48.7, lng: 31},
              zoom: 6
            });

没有x原点限制,您可以按照自己的意愿操作iframe内容。有了它,即使父容器缩放了,一切都没问题

我也有这个问题,上面的解决方案对我不起作用,因为:

  • @Terion的"point2LatLng"函数似乎没有将标记放置在正确的位置
  • @Terion使用虚拟iframe意味着你不能拖动地图,这严重限制了用户体验。

然而,我确实找到了一种方法来做到这一点:我把地图div内的容器,我有效地缩放这个JS,加载后所有其他JS:

//Function: Unscale the map Container
function unscaleMap(scale){
    var unscale = Math.round(10000/(scale * 1))/10000,
        rescale = Math.round(10000 * (100 / unscale))/10000;
    document.getElementById("fs_mapContainer").style.transform = "scale("+unscale+")";
    document.getElementById("fs_mapContainer").style.width = rescale + "%";
    document.getElementById("fs_mapContainer").style.height = 80 * scale + "vh";
}
CSS:

.map_container {position: relative; transform-origin: 0 0; box-sizing: border-box;}
#map {width: 100%; height: 100%}