Last active
July 3, 2020 15:15
-
-
Save guillefd/5481be0499956595f562c5ea1b7a1b2d to your computer and use it in GitHub Desktop.
Angular, get places/address autocomplete predictions with Google Maps Place API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component } from '@angular/core'; | |
import { FormGroup, FormBuilder } from '@angular/forms'; | |
import { } from '@types/googlemaps'; | |
@Component({ | |
selector: 'autocomplete', | |
template: ` | |
<input class="input" | |
type="text" | |
[(ngModel)]="autocompleteInput" | |
(keyup)="searchAddress()"> | |
`, | |
styleUrls: ['./autocomplete.component.scss'] | |
}) | |
export class AutocompleteComponent { | |
autocompleteInput:string; | |
queryWait:boolean; | |
constructor(){} | |
// triggered by input keyup event | |
searchAddress() { | |
console.log('search', this.autocompleteInput); | |
// whenever a search is triggered | |
// a 1 second delay is set to avoid excesive calls to API | |
if(!this.queryWait) { | |
this.queryWait = true; | |
setTimeout(() => { | |
// when timeout, it triggers the search and always reads the last query | |
this.getAutocompletePredictions(); | |
this.queryWait = false; | |
}, 1000); | |
}else{ | |
console.log('wait ...'); | |
} | |
} | |
private getAutocompletePredictions() { | |
if(this.autocompleteInput.length<4) { | |
console.log('query is too short, bye'); | |
return; | |
} | |
this.getPlacePredictions(this.autocompleteInput) | |
.then(data => { | |
console.log('predictions', data); | |
}) | |
.catch(err => console.log(err)); | |
} | |
private getPlacePredictions(query: string): Promise<any> { | |
let autocompleteSrv = new google.maps.places.AutocompleteService(); | |
return new Promise((resolve, reject) => { | |
autocompleteSrv.getPlacePredictions({ | |
types: ['geocode','establishment'], | |
input: query, | |
componentRestrictions: { country: 'AR' } | |
}, function (predictions, status) { | |
if (status == google.maps.places.PlacesServiceStatus.OK) { | |
resolve(predictions); | |
} else { | |
reject(status); | |
} | |
}); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment