Get google.maps.Map instance from a HTMLElement

JavascriptGoogle MapsGoogle Maps-Api-3

Javascript Problem Overview


I have an existing map on a page. I can select that element using something along the lines of document.getElementById() to get the HTMLElement javascript object. Is it possible to get the instance of google.maps.Map created when the map is initialised, i.e. is it a property of the HTMLElement object or in its prototype?

Javascript Solutions


Solution 1 - Javascript

You can't get google.maps.Map object from DOM Element ,on which Google Maps object have been constructed. google.maps.Map is just a wrapper, which controls DOM Element for viewing the map, and that element does not have reference to its wrapper.

If your problem is only the scope, make map as a property of window object, and it will be accessible from everywhere in your page. You can make 'map' as global by using one of these:

 window.map = new google.maps.Map(..) 

or

 map = new google.maps.Map(...) //AVOID 'var' 

Solution 2 - Javascript

You can get google.maps.Map object from DOM Element, with a slight trick.

When you initialize map object, you need to store the object on element's data attribute.

Example:

$.fn.googleMap = function (options) {
    var _this = this;

    var settings = $.extend({}, {
        zoom: 5,
        centerLat: 0,
        centerLon: 0
    }, options);

    this.initialize = function () {
        var mapOptions = {
            zoom: settings.zoom
        };

        var map = new google.maps.Map(_this.get(0), mapOptions);
        // do anything with your map object here,
        // eg: centering map, adding markers' events

        /********************************************
         * This is the trick!
         * set map object to element's data attribute
         ********************************************/
        _this.data('map', map);

        return _this;
    };
    // ... more methods

    return this;
};

After you define a map element, eg:

var mapCanvas = $('#map-canvas');
var map = mapCanvas.googleMap({
    zoom: 5,
    centerLat: 0,
    centerLong: 0
});
// ... add some pre-load initiation here, eg: add some markers
// then initialize map
map.initialize();

you can then get the map object later on by using element's ID, eg:

var mapCanvas = $('#map-canvas');
$('.location').on('click', function () {
    // google map takes time to load, so it's better to get
    // the data after map is rendered completely
    var map = mapCanvas.data("map");
    if (map) {
        map.panTo(new google.maps.LatLng(
            $(this).data('latitude'),
            $(this).data('longitude')
            ));
    }
});

By using this method, you can have multiple maps with different behaviors on a page.

Solution 3 - Javascript

I had a similar problem. All I wanted to do was to manipulate maps after they where created. I tried something like that (I think it will help you too). I've created function (more or less like this):

function load_map(el_id, lat, lng) {
  var point = new google.maps.LatLng(lat,lng);
  var myMapOptions = {
    scrollwheel:false,
    zoom: 15,
    center: point,
    mapTypeControl: true,
    mapTypeControlOptions: {
      style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
      position: google.maps.ControlPosition.RIGHT_TOP
    },
    navigationControl: true,
    navigationControlOptions: {
      style: google.maps.NavigationControlStyle.SMALL,
      position: google.maps.ControlPosition.LEFT_CENTER
    },
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById(el_id),myMapOptions);
  var marker = new google.maps.Marker({
    draggable:true,
    map: map,
    position: point
  });
  return({
    container:map.getDiv(),
    marker:marker,
    mapa:map
  });
}

What this function does is after calling it to create a map in some container.

var mapa = load_map('mapa_container', 53.779845, 20.485712);

Function will return object containing some data used while making the map. After creating a map itself I can simply manipulate, in my case, marker on each map separately using mapa object, for example:

mapa.marker.setPosition(new google.maps.LatLng(20,30));
mapa.mapa.setCenter(new google.maps.LatLng(20,30));

This will change marker position and center map to the same coords. Notice that lng and lat values are different then while calling function that creates a map.

Hope that helps.

Solution 4 - Javascript

You create an instance when you initialize a map;

var map = new google.maps.Map(document.getElementById("map_element"), options);

You use that instance whenever you want to do something like putting a marker, changing location, etc. It's not an HTMLElement object. However it has a getDiv() method, which gives you the html element it's operating on.

map.getDiv(); // in this case it returns the element with the id 'map_element'

Solution 5 - Javascript

If you are using Google-map component from the Polymer project, you can get the existing map Dom like this:

var map = document.querySelector('google-map');

Once you have that, current instance of map can be accessed by:

var currentMapInstance = map.map;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOlly HicksView Question on Stackoverflow
Solution 1 - JavascriptEngineerView Answer on Stackoverflow
Solution 2 - JavascriptgoldskyView Answer on Stackoverflow
Solution 3 - JavascriptThePuebloView Answer on Stackoverflow
Solution 4 - JavascriptkeuneView Answer on Stackoverflow
Solution 5 - JavascriptNaveed Ul IslamView Answer on Stackoverflow