2
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?

EugenSunic
  • 13,162
  • 13
  • 64
  • 86
Dreams
  • 8,288
  • 10
  • 45
  • 71
  • duplicate of [Google Maps getBounds() returns undefined](http://stackoverflow.com/questions/20555582/google-maps-getbounds-returns-undefined) – geocodezip Aug 01 '15 at 10:21

2 Answers2

2

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/

EugenSunic
  • 13,162
  • 13
  • 64
  • 86
0

According to the Google documentation,

getBounds()

Return Value: LatLngBounds Returns the lat/lng bounds of the current viewport. If more than one copy of the world is visible, the bounds range in longitude from -180 to 180 degrees inclusive. If the map is not yet initialized (i.e. the mapType is still null), or center and zoom have not been set then the result is null or undefined.

Hence you must first initialize your map.