Google Maps API - Google Not Defined Error

2019-08-29 03:32发布

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条回答
我命由我不由天
2楼-- · 2019-08-29 04:15

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"
                }
            );
        }
    }
}
查看更多
登录 后发表回答