TypeError:无法读取属性'自动完成' Angular 2

时间:2017-08-23 12:18:00

标签: javascript angular google-maps

我想使用Angular 2 Google地图自动填充功能,我找到了this directive

当我尝试使用它时,它给了我这个错误:

  

errors.ts:42错误错误:未捕获(在承诺中):TypeError:无法读取属性'自动完成'未定义的

我不知道我是否错过了什么。无论如何,这里是指令的代码:

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)">

2 个答案:

答案 0 :(得分:7)

如果您使用谷歌地图,您必须在ngmodule中导入Api,如下所示:

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

使用自动完成模块需要库“places”。

比这样使用它:

    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

答案 1 :(得分:1)

这种方法帮助我摆脱了这个错误。只需将google maps api导入更改为:

https://maps.googleapis.com/maps/api/js?key=YOURAPIKEY

然后将&libraries=places添加到URL的末尾,如下所示:

<script async defer
        src="https://maps.googleapis.com/maps/api/js?key=YOURAPIKEY&libraries=places">
</script>