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?
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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With