Reputation: 11
I want to use an Angular 2 Google map autocomplete and I found this directive.
When I tried to use it, it gives me this error:
errors.ts:42 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'Autocomplete' of undefined
I dont know if I missed something. Anyway, here's the code of the directive:
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);
}
}
Here's how to use it:
<input type="text" class="form-control" placeholder="Location" name="Location" [(ngModel)]="address" #LocationCtrl="ngModel"
Googleplace (setAddress)="getAddressOnChange($event,LocationCtrl)">
Upvotes: 1
Views: 9682
Reputation: 2208
This approach helped me to get the rid of this error. Just change the google maps api import to like this:
https://maps.googleapis.com/maps/api/js?key=YOURAPIKEY
Then add &libraries=places
to the end of URL so it looks like this:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOURAPIKEY&libraries=places">
</script>
Upvotes: 3
Reputation: 865
If you are using google maps you have to import the Api in the ngmodule like this:
@NgModule({
declarations: [...],
imports: [...,
AgmCoreModule.forRoot({
clientId: '<mandatory>',
//apiVersion: 'xxx', // optional
//channel: 'yyy', // optional
//apiKey: 'zzz', // optional
language: 'en',
libraries: ['geometry', 'places']
})
],
providers: [...],
bootstrap: [...]
})
the library 'places' is needed to use the autocomplete module.
Than use it like this:
import {MapsAPILoader} from "@agm/core";
...
constructor(private mapsAPILoader: MapsAPILoader,
...
this.mapsAPILoader.load().then(() => {
let autocomplete = new window['google'].maps.places.Autocomplete(..., ...);
autocomplete.addListener("place_changed", () => { ...
You can take a look here: Angular 2 + Google Maps Places Autocomplete
Upvotes: 13