Galway Galway - 1 month ago 18
Javascript Question

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

I've just started getting into the Google Maps API. This problem is easy to understand but I have no idea how to fix it. This is the simple code sample that Google gives you except for the alert.

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() works FINE when it's called from any other event except for load. When it's a map event like zoom or drag it works fine, but when I try to call it here I get the error "Uncaught TypeError: Cannot read property 'getNorthEast' of undefined". Anyone know what's up here or how I can fix this?

Answer

The Google Maps Javascript API v3 is event based. You need to wait for the first bounds_changed event on the map before the bounds is defined.

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>