aBloomer aBloomer - 2 months ago 10
Javascript Question

Why can't I get latitude and longitude using getBounds function?

var map;

function initialize(location) {

var currentPosition = new google.maps.LatLng(14.457264, 121.024038);
var mapOptions = {
center: currentPosition,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};

map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions)

var marker = new google.maps.Marker({
position: currentPosition,
map: map,
icon: "../images/02_button_add.png"
});

var bounds = map.getBounds();
alert(bounds);
}


Above is my code, I can have my current position on map.
However, the getBounds function is not working when trying to alert with information,it gives "undefined" value as a result.

Is anything wrong?

Answer

You have to implement a listener in order for your getBounds() to display correctly

I suggest this code (EDIT):

 google.maps.event.addListenerOnce(map, 'idle', function(){

   var bounds = map.getBounds();
   alert(bounds);
});

Here is your fiddle so you can test it (after it loads click run again): http://jsfiddle.net/vA4eQ/280/