kapetanios kapetanios - 15 days ago 5
Javascript Question

re-sizing and re-centering a google map without access to a global variable "map"

I have google maps implemented on my page and i want to be able to resize and recenter it After a particular event. Here is code i have found on the internet:

var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);


Now this is all cool but i dont have access to a "map" global. Instead i have been able to use a jquery selector to get the map-canvas DOM like so:

google.maps.event.trigger($("#map-canvas")[0], 'resize');


but using
$("#map-canvas")[0];
doesnt work when i try to call getCenter() and setCenter(). Any ideas why?

thanks

Answer

Your map variable is an instance of google map object, but your $("#map-canvas")[0] is a DOM element, so you can't call any method because google won't recognize it.

In your case, it may just be a scope problem

Why don't you just put your map variable global and call it everywhere e.g:

var map; // my google map object

$(document).ready(function(){
  var center = map.getCenter();
  google.maps.event.trigger(map, "resize");
  map.setCenter(center);
});

And then, whenever you call map.getCenter(); it should return you the value (only if you already create the google object, obviously)

Comments