如何知道Google地点何时加载并准备好(异步)?

Ala*_*ink 1 jquery google-maps-api-3 google-places-api

我在JQuery中异步加载谷歌地图和地点:

 var script = document.createElement('script');
 script.type = 'text/javascript';
 script.src = "http://maps.google.com/maps/api/js?key=myKey&libraries=places&sensor=false&async=2&callback=MapApiLoaded";
 document.body.appendChild(script);
Run Code Online (Sandbox Code Playgroud)

加载Google地图时会调用回调:

function MapApiLoaded() {

   var input = document.getElementById('searchField');
   var options = {
      types: ['(cities)'],
   };

   autocomplete = new google.maps.places.Autocomplete(input, options);

   google.maps.event.addListener(autocomplete, 'place_changed', function(event) {
        var item = autocomplete.getPlace();
        // do some stuff
    }
    GMapsloaded = true;
 }
Run Code Online (Sandbox Code Playgroud)

当我进入我的城市选择屏幕时,我先检查是否已加载Google地图:

 if(!GMapsloaded) {
    alert('mapsnotloaded');
    return;
  }
Run Code Online (Sandbox Code Playgroud)

当我的手机处于Wifi或3G时,我可以开始在占位符中输入并且谷歌地方会响应.当我在Edge时,我开始打字,谷歌地方没有任何互动.当我输入第一个字母时,我可能需要2分钟才能得到任何反应.

我真的只想在Places准备就绪时真正开始输入输入文本.但是我没有找到任何要绑定的事件.

任何的想法 ?谢谢

Ala*_*ink 6

找到了解决方案.我希望它会帮助某人(我花了4个小时):

// When Google places is ready, it adds an attr placeholder='Enter a location' or the equivalent in the current language
// It is the only way to know that it is monitoring the input field.
if (!GMapsloaded || $('#searchField').attr('placeholder') === undefined || $('#searchField').attr('placeholder') == false) {
    alert('Google places not attached to input');
    return;
}
Run Code Online (Sandbox Code Playgroud)