Last active
July 10, 2016 00:07
-
-
Save ihadeed/f11f1e9646a2d4f562aa6fd5805ab2b5 to your computer and use it in GitHub Desktop.
Angular2 Component: Google Maps Places AutoComplete
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, ElementRef, Output, EventEmitter, AfterViewInit, OnDestroy} from '@angular/core'; | |
declare var google: any; | |
@Component({ | |
selector: 'places-auto-complete', | |
template: ` | |
<input type="text"> | |
` | |
}) | |
export class PlacesAutoCompleteComponent implements AfterViewInit, OnDestroy { | |
@Output() placeChange: EventEmitter<any> = new EventEmitter<any>(); | |
private autoComplete: any; | |
constructor(private el: ElementRef){ | |
if(typeof google == 'undefined') console.warn('Unable to detect loaded Google JavaScript API.'); | |
} | |
ngAfterViewInit(): void { | |
let input: HTMLInputElement = this.el.nativeElement.children[0]; | |
this.initAutoComplete(input); | |
} | |
ngOnDestroy(): void { | |
google && google.maps && google.maps.event && google.maps.event.clearListeners(this.autoComplete, 'place_changed'); | |
} | |
private initAutoComplete(input: HTMLInputElement): void { | |
this.autoComplete = new google.maps.places.Autocomplete(input); | |
google && google.maps && google.maps.event && google.maps.event.addListener(this.autoComplete, 'place_changed', () => { | |
this.placeChange.emit(this.autoComplete.getPlace()); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment