Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google maps places autocomplete loading events

I'm using the Google Maps Places Autocomplete api.

I would like to show an Ajax spinner during the search, before the autocomplete dropdown is displayed.

How can I determine when the places results are ready? Is there some event fired off?

This is particularly helpful on bad internet connections since the latency can sometimes be up to 5 seconds. The user needs to know the search box is an autocomplete inputbox before frantically pressing enter to search.

like image 451
Tarang Avatar asked Jun 14 '14 10:06

Tarang


1 Answers

You could use the autocomplete service to get the query predictions. It has a callback function.

On the example from the link you provided, you could declare input as a global variable in the script. And access it with the autocomplete service after the initialize function:

var input;
function initialize () {
  ...
  input = document.getElementById('pac-input');
  ...
}

function showSpinner() {
  document.getElementById('spinner').style.display = 'block';

  var service = new google.maps.places.AutocompleteService();
  service.getQueryPredictions({ input: input }, callback);
}

function callback(predictions, status) {
  if (status != google.maps.places.PlacesServiceStatus.OK) {
    document.getElementById('spinner').style.display = 'none';
    return;
  }
}

As for the changes in the html document:

  <body>
    <input id="pac-input" class="controls" type="text"
        placeholder="Enter a location" onkeypress="showSpinner()">
    <img id="spinner" src="spinner.gif" style="position:absolute; top:0; right:0; width: 250px; display: none">
  </body>

I would run this only if a one-second timeout (i.e. if the user's internet connection is slow), otherwise the spinner looks like a subliminal image.

like image 70
agaudin Avatar answered Oct 13 '22 13:10

agaudin