uneeb meer uneeb meer - 5 months ago 44
Javascript Question

load google map without using callback method

i have multiple google map instances on my website,now there are two different google map on a same page, what happens is the first one works and other doesn't now i know the logical issue let me show you my code first





<script>
function initMap() {
var myLatLng = {lat: 43.6222102, lng:-79.6694881};

var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: myLatLng
});

var marker = new google.maps.Marker({
position: myLatLng,
map: map,
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=my_key&callback=initMap"
async defer></script>


now as i defined a callback method it always initializes the method named initMap whereas what i want to do is there can be multiple google maps lets suppose initMap2 how can i load them without callback method?

Answer Source

To load the map without a callback, load the API synchronously/inline (without the async defer), then call your initMap function on the load event.

proof of concept fiddle

code snippet:

function initMap() {
  var myLatLng = {
    lat: 43.6222102,
    lng: -79.6694881
  };

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 15,
    center: myLatLng
  });

  var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
  });
}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>