【问题标题】:Javascript Google Place API library not getting loaded dynamicallyJavascript Google Place API 库未动态加载
【发布时间】:2015-06-03 12:17:54
【问题描述】:

我的javascript代码

var script = document.createElement('script');
script.src = 'https://maps.googleapis.com/maps/api/js?libraries=places';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
script.onload = function(){
var  autocomplete;

  autocomplete = new google.maps.places.Autocomplete(
     (document.getElementById('autocomplete')),
      { types: ['geocode'] });

我收到此错误

Cannot read property 'Autocomplete' of undefined
    at HTMLScriptElement.script.onload (mabapamavo.js:18:40)

当我使用脚本标签加载库时,上述相同的代码有效。但我想使用 Javascript 动态加载库。

我犯了什么错误?

【问题讨论】:

    标签: javascript autocomplete google-places-api


    【解决方案1】:

    错误消息告诉您google.maps.places 未定义。而不是使用script.onload,您应该使用初始化回调,如in the documentation 所述。

    你的代码应该是这样的:

    var script = document.createElement('script');
    script.src = 'https://maps.googleapis.com/maps/api/js?libraries=places&callback=initialize';
    script.type = 'text/javascript';
    document.getElementsByTagName('head')[0].appendChild(script);
    
    initialize = function() {
        var autocomplete = new google.maps.places.Autocomplete(
          (document.getElementById('autocomplete')), {
            types: ['geocode']
          });

    【讨论】:

    • 谢谢布伦特布鲁姆:) 上面的解决方案解决了它!
    【解决方案2】:

    当您异步加载 Maps API 时,您不会使用 onload 事件处理程序。相反,您在加载 API 的 URL 中传递回调函数的名称。关注this example,它会起作用的。

    【讨论】:

      猜你喜欢
      • 2011-12-12
      • 2018-10-20
      • 2017-01-15
      • 1970-01-01
      • 2020-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-02
      相关资源
      最近更新 更多