用于地址自动填充的Google API无效

时间:2015-10-13 09:38:37

标签: jquery google-maps google-api siebel

我尝试在我的Siebel应用程序中的一个文本字段上使用Google API实现地址自动完成功能。我一直收到错误“google not defined”。我正在使用jquery以下是我的代码:

     PhoneChangePR.prototype.BindData = function(a) {
                SiebelAppFacade.PhoneChangePR.superclass.BindData.call(this, a);
$.getScript("http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js", function() {
            console.log("Google maps successfully added");
            });
                  $.getScript("http://maps.google.com/maps/api/js?sensor=false&libraries=places&language=en-AU", function() {
            console.log("Second script loaded successfully");
            });


             var autocomplete = new google.maps.places.Autocomplete($("input[aria-labelledby=NewAddressLine1_Label]")[0], {});

                google.maps.event.addListener(autocomplete, 'place_changed', function() {
                    var place = autocomplete.getPlace();
                    console.log(place.address_components);
    });

请帮助。谢谢。

1 个答案:

答案 0 :(得分:1)

您正在异步加载Google地图API,但您在加载API之前尝试调用google.maps.places.Autocomplete构造函数。

将依赖于加载的API的所有代码移动到成功回调中。

PhoneChangePR.prototype.BindData = function(a) {
    SiebelAppFacade.PhoneChangePR.superclass.BindData.call(this, a);
    $.getScript("http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js", function() {
        console.log("jQuery successfully loaded");
    });

    $.getScript("http://maps.google.com/maps/api/js?sensor=false&libraries=places&language=en-AU", function() {
        console.log("Google maps successfully added");
        var autocomplete = new google.maps.places.Autocomplete($("input[aria-labelledby=NewAddressLine1_Label]")[0], {});

        google.maps.event.addListener(autocomplete, 'place_changed', function() {
            var place = autocomplete.getPlace();
            console.log(place.address_components);
        });
    });
});

通过在加载请求中添加callback URL参数,您可能希望在地图JS成功加载后使用Google自己的回调,而不是依赖于jQuery的成功回调Maps API。试试这个:

PhoneChangePR.prototype.BindData = function(a) {
    SiebelAppFacade.PhoneChangePR.superclass.BindData.call(this, a);
    $.getScript("http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js", function() {
        console.log("jQuery successfully loaded");
    });

    $.getScript("http://maps.google.com/maps/api/js?sensor=false&libraries=places&language=en-AU&callback=setupAutocomplete");
});

function setupAutocomplete() {
    console.log("Google maps successfully added");
    var autocomplete = new google.maps.places.Autocomplete($("input[aria-labelledby=NewAddressLine1_Label]")[0], {});

    google.maps.event.addListener(autocomplete, 'place_changed', function() {
        var place = autocomplete.getPlace();
        console.log(place.address_components);
    });
}