Dean Gibson Dean Gibson - 5 months ago 33
Javascript Question

Get Instance of Google Maps Object Using JQuery

I'm looking at writing a function that when called will fetch an instance of a Google Maps object on the page if there is one present, using JQuery.

For instance if there is indeed a Map on the page, it would look something like this:

<div class="map">....</div>

So getting access to the div containing the map is easy enough. i.e.
. But how do you then cast it so that it's actually of type Google Map Class and then be able to call functions on it and access properties?


You can't, unless the JavaScript code that creates the Google Map object makes it very easy for you.

The Google Maps object is completely independent of the DOM element used to display it. There is no way to access the JavaScript object in reverse given access to its DOM element or with jQuery. (Even if you could, looking for a div with a "map" class wouldn't necessarily be fruitful because the map's DOM element can have arbitrary class names and ID.)

In order to access the Google Maps JavaScript object you would have to be able to get at the reference to the variable for the instantiated Google Maps object. And the only way that would be possible is if the object is somewhere in the global namespace that you can access it. And even then you would need to manually scan the entire global namespace to try and find a valid Map, or know ahead of time where the variable is located. is an example I know of where the Google Map object has been added to the global namespace. In the map editor, it's accessible as However, you absolutely cannot count on every Google Map in the wild being this accessible. They might be a private variable, inside a closure or anonymous function, etc. So don't bet on it.