问题
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);
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;
}
When I Get into my city selection screen, I check first that Google maps has been loaded :
if(!GMapsloaded) {
alert('mapsnotloaded');
return;
}
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.
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
回答1:
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;
}
来源:https://stackoverflow.com/questions/17135608/how-to-know-when-google-places-has-loaded-and-is-ready-asynchronously