Google Maps API - Google Not Defined Error

2019-08-29 04:01发布

问题:

I am try to use the Google Maps API in my Backbone application, but I get an error. Here is my code:

var MyView = MyParrentView.extend({
    events: {
       //my events
    },
    initialize: function (options) {
        $('head').append('<script src="https://www.google.com/jsapi?key=MyAPIKey" type="text/javascript"></script>');  


   if (google != undefined) {
                google.load(
                    "earth",
                    "1",
                    {
                        "other_params":"sensor=false"
                    }
                );
            }
  }
 ,

At if (google != undefined) { line, I get the error: ReferenceError: google is not defined. Can anyone point me in the right direction to fix this or why this is happening? I'm pretty new to using Google's API.

Thanks

回答1:

Try this: The callback won't be executed until the script is loaded.

var MyView = MyParrentView.extend({
    events: {
       //my events
    },
    initialize: function (options) {
        $.ajax({url: 'https://www.google.com/jsapi?key=MyAPIKey&language=EN&callback=onGoogleMapsLoaded',dataType: 'script'});
    },

    onGoogleMapsLoaded : function(){
        if (google != undefined) {
            google.load(
                "earth",
                "1",
                {
                    "other_params":"sensor=false"
                }
            );
        }
    }
}