Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 468
Galway Avatar asked Nov 21 '25 06:11

Galway


2 Answers

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?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map"></div>
like image 101
geocodezip Avatar answered Nov 22 '25 21:11

geocodezip


the getBounds() method requires the map tiles to finish loading to return correct results. but you can get it using bounds_changed event, which is fired even before the tiles are loaded. so try using this:

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

for preventing alert multiple time you can use google.maps.event.addListenerOnce

like image 35
Suchit kumar Avatar answered Nov 22 '25 21:11

Suchit kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!