I have a div on my page called ‘map’, and I set google map in it:
(function () {
window.onload = function () {
var mapDiv = document.getElementById('map');
var latlng = new google.maps.LatLng('@lng', '@lat');
var options = { styles: styleArray,
center: latlng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(mapDiv, options);
...
Now I have some other functions and I need reference to this map div so I can add markers on it.
So how I can get reference to this dic with map to get map object?
I tried this way but it doesn’t work:
var map = new google.maps.Map(document.getElementById("map"));
Your attempt does not work because that is creating a new
google.maps.Mapinstance.mapneeds to be declared a global variable. At least it needs to be declared a variable outside of the function which reference you assign towindow.onload. JavaScript 101.