谷歌地图JS API-如何使用fitBounds响应地图

Google Maps JS API - How to use fitBounds for responsive map?

本文关键字:fitBounds 响应 地图 何使用 JS API- 谷歌地图      更新时间:2024-03-07

我正试图在响应式网站的地图中显示某个区域。我希望它在加载时通过放大和缩小显示相同的区域,无论窗口大小如何。经过一些研究,我知道我需要使用谷歌地图JS API的fitBounds函数,但无法使其工作。到目前为止,这是我的代码:

<div id="map"></div><!--css rules to make it a 16/9 responsive box-->
<script src="https://maps.googleapis.com/maps/api/js?key=mykey" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng(x, y), //any coordinates I put here don't matter, as I need the map to adjust using bounds, right?
        zoom: 11
    };
    var bounds = google.maps.LatLngBounds(
        new google.maps.LatLng(x, y), //SW coordinates here
        new google.maps.LatLng(x, y) //NE coordinates here
    );
    var map = new google.maps.Map(document.getElementById("map"), mapOptions);
    map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
    var bounds = map.getBounds();
    google.maps.event.trigger(map, "resize");
    map.fitBounds(bounds);
});
</script>

地图似乎只是显示了选项中的中心位置,而忽略了fitBounds调用。我错过了什么/做错了什么?

在有机会调整之前,您正在检索地图的边界

您需要为map resize事件添加一个额外的处理程序,然后将fitBounds代码移到其中。仍然在窗口调整大小处理程序中保留映射调整大小的触发器。

编辑

您需要将映射变量移到initialize函数之外,以便映射侦听器

可以全局访问它

以下是它的实现方式(使用jQuery窗口调整大小事件):

function initialize() {
  var mapOptions = {
    center: new google.maps.LatLng(x, y),
    zoom: 11
  };
  var bounds = google.maps.LatLngBounds(
    new google.maps.LatLng(x, y), //SW coordinates here
    new google.maps.LatLng(x, y) //NE coordinates here
  );
  var map = new google.maps.Map(document.getElementById("map"), mapOptions);
  map.fitBounds(bounds);
  // Listen for events after map initialization
  $(window).resize(function() {
    google.maps.event.trigger(map, 'resize');
  });
  google.maps.event.addListener(map, 'resize', function() {
    var bounds = map.getBounds();
    map.fitBounds(bounds);
  });
}
google.maps.event.addDomListener(window, 'load', initialize);