如何知道Google地点何时加载并准备好(异步)? [英] How to know when Google places has loaded and is ready (asynchronously)?

查看:125
本文介绍了如何知道Google地点何时加载并准备好(异步)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I load google maps and places asynchronously in 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);

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

The callback is called when Google Maps has loaded :

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;
 }

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

When I Get into my city selection screen, I check first that Google maps has been loaded :

 if(!GMapsloaded) {
    alert('mapsnotloaded');
    return;
  }

当我的手机是在Wifi或3G上,我可以开始在占位符和谷歌地方输入回应,当我在边缘时,我开始打字,并且没有谷歌地点的互动,在我实际得到任何反应时,可能需要2分钟。输入第一个字母。

When my mobile is in Wifi or 3G, I can start typing in the placeholder and google places responds. When I'm in Edge, I start typing and there's no interaction from google places. It could take up to 2 minutes before I actually get any reaction when I type the first letter.

我只想在Places真的准备好时能够真正开始输入输入文本,但是我没有发现任何事件绑定到。

I'd like to only be able to actually start typing in the input text when Places is really ready. But I haven't found any event to bind to.

任何想法?谢谢

Any idea ? Thank you

推荐答案

找到解决方案。我希望它能帮助别人(我已经花了4个小时):

Found a solution. I hope it will help someone (I've spent 4 hours on this) :

// 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;
}

这篇关于如何知道Google地点何时加载并准备好(异步)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆