2017-08-23 79 views
0

我想使用Angular 2 Google地圖自動完成功能,並且我找到了this directiveTypeError:無法讀取Angular 2中未定義的屬性'Autocomplete'

當我試圖使用它,它給了我這個錯誤:

errors.ts:42 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'Autocomplete' of undefined

我不知道如果我錯過了什麼。總之,這裏的指令代碼:

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); 
} 
} 

下面是如何使用它:

<input type="text" class="form-control" placeholder="Location" name="Location" [(ngModel)]="address" #LocationCtrl="ngModel" 
    Googleplace (setAddress)="getAddressOnChange($event,LocationCtrl)"> 
+0

你肯定'google.maps.places'定義? – Nolyurn

+0

感謝您的回答,但我只是複製代碼,因爲它是 –

+0

我必須安裝依賴關係? –

回答

3

如果您在使用谷歌地圖,你必須導入API中的ngmodule這樣的:

@NgModule({ 
    declarations: [...], 
    imports: [..., 
    AgmCoreModule.forRoot({ 
     clientId: '<mandatory>', 
     //apiVersion: 'xxx', // optional 
     //channel: 'yyy', // optional 
     //apiKey: 'zzz', // optional 
     language: 'en', 
     libraries: ['geometry', 'places'] 
    }) 
    ], 
    providers: [...], 
    bootstrap: [...] 
}) 

使用自動完成模塊需要庫'位置'。

不是使用這樣的:

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",() => { ... 

你可以在這裏看看:Angular 2 + Google Maps Places Autocomplete

+0

使用'window ['google']'爲我工作 – Manoj

相關問題