getBounds() in Google Maps API v3
If you need to know the latitude and longitude for the corners of the visible area of the google map, you’ll probably use something like getBounds();
In Google Maps API v2, to get them, you will do something like this:
var bounds = map.getBounds();
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
But in API v3 you will get “bounds is undefined” error.
So to get our latitude and longitude we need to move getBounds(), to some event listener.
Most common probably will be bounds_changed:
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 10,
center: new google.maps.LatLng(lat, lng),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
//do whatever you want with those bounds
});
</script>
Description of bounds_changed in documentation is: “This event is fired when the viewport bounds have changed.”
It seems, that it’s the best moment to get our bounds. But if you want to make some ajax call in it, then every time when position of map has changed the ajax call will be fired. Most of the time we don’t need to firing ajax until we get our final map. With this event every zoom or panning will fire ajax call.
In my opinion, better solution is to use event “idle”. Especially if you want to make that ajax call. Description says: “This event is fired when the map becomes idle after panning or zooming.”. So the code will look like that:
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 10,
center: new google.maps.LatLng(lat, lng),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
google.maps.event.addListener(map, 'idle', function() {
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
//do whatever you want with those bounds
});
</script>
But you can choose event which will suits your needs, not mine ;o). Just read description of them in documentation of google.maps.Map class – section events and decide which one is best for you.
thanks very much
hi
thanks for this Work
I tested the code and I receive the error => uncaught reeference Error: google is not defined
have you a idea !!
You might be calling it before you load google. How are you loading the library? Async? Header? etc…
There is no stupid questions ;o) only stupid answers
Anyway, I have no idea. And don't have time right time to look. But check what value have zoom and other options when viewport is bigger than earth. Maybe that will give you some clues how to do that.
Maybe a stupid question:
Is there any way to find out, that the viewport is bigger than earth?
How to detect, that maybe the NE corner is (10,10) and the SW corner is (30,30) but in between there could be the full earth?
Any ideas?
Thank you!
– Rainer