map.getBounds()奇怪的行为(Uncaught TypeError:无法读取属性' getNorthEast' of undefined)

时间:2015-01-07 04:26:54

标签: javascript google-maps

我刚刚开始使用Google Maps 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()从除load之外的任何其他事件调用时工作FINE。当它是一个像缩放或拖动的地图事件时,它工作正常,但当我尝试在这里调用它时,我得到错误“Uncaught TypeError:无法读取未定义的属性'getNorthEast'”。任何人都知道这里有什么或我如何解决这个问题?

2 个答案:

答案 0 :(得分:7)

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>

答案 1 :(得分:1)

getBounds()方法要求地图图块完成加载以返回正确的结果。 但你可以使用bounds_changed事件来获取它,甚至在加载图块之前就会触发它。 所以试着用这个:

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

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

相关问题