9

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?

0

1 Answer 1

19

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.