Steven
Steven

Reputation: 19425

Google Maps and loading scripts async - how to order the loading?

If I understand this correctly, using defer will load the scripts in the order I put them.

This will allow me to load jQuery before my own function (because it's lighter and laods more quickly). I load Google Maps at the bottom because it has a callback to a function inside tv-modal.js.

<script src="js/jquery.min.js" defer></script>
<script src="js/tv-modal.js" defer></script>
<script src="https://maps.googleapis.com/maps/api/js?key=abc&callback=modalMap.initMap" defer></script>

My Js looks like this:

var modalMap = {
    map: null,

    init: function() {
        var self = this;
        this.map = $('#modal-g-map');
    },

    initMap: function(){
        map = new google.maps.Map(document.getElementById('modal-g-map'), {
            center: {lat: 59.9071401, lng: 10.7711175},
            zoom: 11
        });
    }

}.init();

But Google Map isn't happy:

Uncaught InvalidValueError: modalMap.initMap is not a function

Why can't Google Maps callback call my function modalMap.initMap?

Upvotes: 1

Views: 325

Answers (2)

Dr.Molle
Dr.Molle

Reputation: 117334

modalMap is not this:

{
    map: null,

    init: function() {
        var self = this;
        this.map = $('#modal-g-map');
    },

    initMap: function(){
        map = new google.maps.Map(document.getElementById('modal-g-map'), {
            center: {lat: 59.9071401, lng: 10.7711175},
            zoom: 11
        });
    }

}

....you set it to the return-value of the init-method of the object above. The init-method returns nothing, so modalMap is undefined.

You must return the object in the init-method:

init: function() {
    var self = this;
    this.map = $('#modal-g-map');
    return this;//<--return the object
}

Upvotes: 1

Alex
Alex

Reputation: 10216

I guess the way the API fires the function it does not recognize that initMap is a function of the object modalMap by just typing "modalMap.initMap" and hence is not a valid function name. Try to create a function outside of that object like so:

function apiCallback() {
  modalMap.initMap();
}

and adjust your callback parameter:

&callback=apiCallback

Upvotes: 0

Related Questions