uneeb meer
uneeb meer

Reputation: 973

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?

Upvotes: 9

Views: 22622

Answers (1)

geocodezip
geocodezip

Reputation: 161324

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.

(Note: FYI: Google changed all their examples to using asynchronous loading to improve the load times)

(Note2: Google has added a "sample" to their documentation describing synchronous loading)

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
}
<!-- added 1/21/2023 to prevent:
Loading the Google Maps JavaScript API without a callback is not supported: https://developers.google.com/maps/documentation/javascript/url-params#required_parameters
-->
<script>
function dummy() {}
window.dummy=dummy;
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=dummy"></script>
<div id="map"></div>

Upvotes: 19

Related Questions