Google Maps JS API - 如何将 fitBounds 用于响应式地图?

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

我正在尝试在响应式网站的地图中显示特定区域。 我希望它在加载时显示相同的区域,无论 window 大小是多少,都可以通过放大和缩小来显示。 经过一些研究,我明白我需要使用 Google Maps 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 调用。我 missing/doing 哪里错了?

您目前正在检索地图的边界,然后它才有机会调整大小

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

编辑

您需要将地图变量移到初始化函数之外,以便您的地图侦听器可以全局访问它

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

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);