map.getBounds() weird behaviour (Uncaught TypeError: Cannot read property 'getNorthEast' of undefined)

map.getBounds() weird behaviour (Uncaught TypeError: Cannot read property 'getNorthEast' of undefined)

我刚刚开始使用 Google 地图 API。这个问题很容易理解,但我不知道如何解决。这是 Google 为您提供的简单代码示例,但警报除外。

function initialize() {
    var mapOptions = {
        center: { lat: 43.680039, lng: -79.417076},
        zoom: 13
    };
    map = new google.maps.Map(document.getElementById('map'), mapOptions);
    google.maps.event.addListener(map, 'dragend', change );
    google.maps.event.addListener(map, 'zoom_changed', change );

    alert(map.getBounds().getNorthEast().lat());
}
google.maps.event.addDomListener(window, 'load', initialize);

map.getBounds().getNorthEast().lat() 在从除加载以外的任何其他事件调用时工作正常。当它是像缩放或拖动这样的地图事件时,它工作正常,但是当我尝试在此处调用它时,我收到错误 "Uncaught TypeError: Cannot read property 'getNorthEast' of undefined"。有人知道这里发生了什么或我该如何解决这个问题吗?

getBounds() 方法需要地图图块完成加载才能获得 return 正确的结果。 但您可以使用 bounds_changed 事件获取它,该事件甚至在加载图块之前就已触发。 所以尝试使用这个:

google.maps.event.addListener(map, 'bounds_changed', function() {
        alert(map.getBounds().getNorthEast().lat());
     });

为了防止多次警报,您可以使用 google.maps.event.addListenerOnce

Google Maps Javascript API v3 是基于事件的。在定义边界之前,您需要等待地图上的第一个 bounds_changed 事件。

var map;
function initialize() {
  var mapOptions = {
    center: {
      lat: 43.680039,
      lng: -79.417076
    },
    zoom: 13
  };
  map = new google.maps.Map(document.getElementById('map'), mapOptions);
  // google.maps.event.addListener(map, 'dragend', change);
  // google.maps.event.addListener(map, 'zoom_changed', change);
  google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
    alert(map.getBounds().getNorthEast().lat());
  });
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
  height: 100%;
  width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>