ReferenceError:页面刷新后未定义google

时间:2019-01-08 14:34:19

标签: javascript angular google-maps angular6

我在我的网站上使用Google Places API进行自动提示,“先去试试”可以正常工作,但是当我刷新特定角度组件上的页面时,会显示错误消息

ReferenceError: google is not defined

我已经搜索了一些网站,但是没有一种解决方案有效,我尝试在async的脚本标记中添加deferindex.html,但是无效

register.component.ts

declare var google: any;
export class RegisterComponent implements AfterViewInit {
   constructor() { }
   ngAfterViewInit() {
      const input = <HTMLInputElement>document.getElementById('googlePlaces');
      const autocomplete = new google.maps.places.Autocomplete(input, { types: ['geocode'] });
      google.maps.event.addListener(autocomplete, 'place_changed', () => {
       this.place = autocomplete.getPlace();
      })
   }
}

register.component.html

<input id="googlePlaces" type="text" class="input-custom" formControlName="location" placeholder="Enter Place">

并且我已经在主index.html文件中添加了具有有效API密钥的脚本,因为该脚本在第一次使用时就可以正常运行

2 个答案:

答案 0 :(得分:1)

您未使用正确的方式以角度初始化谷歌地图

看看下面的代码,您会在Google上找到自己的幸福:)

this._mapsAPILoader.load().then(() => {
      let autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocompleteInput'), {});
      google.maps.event.addListener(autocomplete, 'place_changed', () => {
        this._ngZone.run(() => {
          const place = autocomplete.getPlace();
          ...
       });
     ...
   });

mapsAPILoader和ngZone必须添加到构造函数中

 constructor(
      private _mapsAPILoader: MapsAPILoader,
      private _ngZone: NgZone) { }

如果有帮助,请毫不犹豫地投票;)

答案 1 :(得分:0)

您可以尝试:

let listen; 
    this._mapsAPILoader.load().then(() => {
      let autocomplete = new  google.maps.places.Autocomplete(document.getElementById('autocompleteInput'), {});
      listen = google.maps.event.addListener(autocomplete, 'place_changed', () => {
        this._ngZone.run(() => {
          const place = autocomplete.getPlace();
          ...
       });
     ...
   });
...
        google.maps.event.removeListener(listen); // then you can reload autocomplete without problens