Retrieving Autocomplete Predictions

by Annie Lagang

HTML

<div id="right-panel">

  <input id="address" placeholder="UK address" value="79 Lowther Road"/>
  <button type="button" onclick="search()">Submit</button>

  <p>Results:</p>
  <ul id="results"></ul>
</div>
<!-- Replace the value of the key parameter with your own API key. -->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&libraries=places"
        async defer></script>

CSS

/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */
#map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#right-panel {
  font-family: 'Roboto','sans-serif';
  line-height: 30px;
  padding-left: 10px;
}

#right-panel select, #right-panel input {
  font-size: 15px;
}

#right-panel select {
  width: 100%;
}

#right-panel i {
  font-size: 12px;
}

JavaScript

// This example retrieves autocomplete predictions programmatically from the
// autocomplete service, and displays them as an HTML list.

// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

function search() {
  var displaySuggestions = function(predictions, status) {
    if (status != google.maps.places.PlacesServiceStatus.OK) {
      alert(status);
      return;
    }

		document.getElementById("results").innerHTML = '';
    
    var arrPr = []; 
    predictions.forEach(function (prediction) {
      arrPr.push(getPredictionDetails(prediction.place_id));
    });
    
    Promise.all(arrPr).then(function(results) {
  			results.forEach(function(result) {
      		console.info('Result: ' + JSON.stringify(result, 4));
      		var li = document.createElement('li');
      		li.appendChild(document.createTextNode(result.formatted_address));
          document.getElementById('results').appendChild(li);
        });	
		}).catch(err => {
    		console.log(err);
    });
  };
  
  function getPredictionDetails(placeId) {
  	let promise = new Promise( (resolve, reject) => {
				placeService.getDetails({
        	 placeId: placeId
        }, function(result, status) {
        		if (status === google.maps.places.PlacesServiceStatus.OK) {
            		resolve(result);
            } else {
            		reject(status);
            }
        });        
    });
    
    return promise;
  }

  var query = document.getElementById("address").value;
  var restrictions = {country: 'uk'};
  var service = new google.maps.places.AutocompleteService();
  var placeService = new google.maps.places.PlacesService(document.getElementById("results"));
  service.getPlacePredictions({ input: query, types: ['geocode', 'add(region)'], componentRestrictions: restrictions },  displaySuggestions);
}