Google Places Autocomplete + Angular2
import {Directive, ElementRef, EventEmitter, Output} from '@angular/core';
import {NgModel} from '@angular/forms';
declare var google:any;
@Directive({
selector: '[Googleplace]',
providers: [NgModel],
host: {
'(input)' : 'onInputChange()'
}
})
export class GoogleplaceDirective {
@Output() setAddress: EventEmitter<any> = new EventEmitter();
modelValue:any;
autocomplete:any;
private _el:HTMLElement;
constructor(el: ElementRef,private model:NgModel) {
this._el = el.nativeElement;
this.modelValue = this.model;
var input = this._el;
this.autocomplete = new google.maps.places.Autocomplete(input, {});
google.maps.event.addListener(this.autocomplete, 'place_changed', ()=> {
var place = this.autocomplete.getPlace();
this.invokeEvent(place);
});
}
invokeEvent(place:Object) {
this.setAddress.emit(place);
}
onInputChange() {
console.log(this.model);
}
}
To use
<input type="text" class="form-control" placeholder="Location" name="Location" [(ngModel)]="address" #LocationCtrl="ngModel"
Googleplace (setAddress)="getAddressOnChange($event,LocationCtrl)">
@Habeeb's answer is a great start, but this is a cleaner implementation. First install the googlemaps typings npm install --save-dev @types/googlemaps
and import them somewhere in your app import {} from '@types/googlemaps'
.
import { Directive, ElementRef, EventEmitter, OnInit, Output } from '@angular/core';
@Directive({
// xx is your app's prefix
selector: '[xxPlaceLookup]'
})
export class PlaceLookupDirective implements OnInit {
@Output() onSelect: EventEmitter<any> = new EventEmitter();
private element: HTMLInputElement;
constructor(el: ElementRef) {
this.element = el.nativeElement;
}
ngOnInit() {
const autocomplete = new google.maps.places.Autocomplete(this.element, {
types: ['establishment'],
componentRestrictions: {country: 'us'}
});
google.maps.event.addListener(autocomplete, 'place_changed', () => {
const place = autocomplete.getPlace();
this.onSelect.emit(place);
});
}
}