Dreams
Dreams

Reputation: 8506

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?

Upvotes: 2

Views: 351

Answers (2)

user2230470
user2230470

Reputation:

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.

Upvotes: 0

EugenSunic
EugenSunic

Reputation: 13703

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/

Upvotes: 2

Related Questions