在 ionic 4 中集成 google 映射时出错

Error in integrating google map in ionic 4

我正在尝试将 google 地图集成到 ionic 4 应用程序中,不幸的是遇到 nativeElement not found 错误。

@ViewChild('Map') mapElement: ElementRef; ~~~~~~~~~~~~~~~~

node_modules/@angular/core/core.d.ts:8436:47 8436(选择器:类型 | 函数 | 字符串,选项:{ ~~~~~~~ 8437 读取?:任何; ~~~~~~~~~~~~~~~~~~~ 8438 静态:布尔值; ~~~~~~~~~~~~~~~~~~~~~~~~ 8439 }): 任何; ~~~~~ 未提供 'opts' 的参数。 系统控制台。

home.page.ts

import {Component, ElementRef, NgZone, ViewChild, OnInit} from '@angular/core';
import {Geolocation} from '@ionic-native/geolocation/ngx';

declare var google: any;
@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
    @ViewChild('Map') mapElement: ElementRef;
    map: any;
    mapOptions: any;
    location = {lat: null, lng: null};
    markerOptions: any = {position: null, map: null, title: null};
    marker: any;
    apiKey: any = 'API_KEY'; 

  constructor(public zone: NgZone, public geolocation: Geolocation) {
    /*load google map script dynamically */
      const script = document.createElement('script');
      script.id = 'googleMap';
      if (this.apiKey) {
          script.src = 'https://maps.googleapis.com/maps/api/js?key=' + this.apiKey;
      } else {
          script.src = 'https://maps.googleapis.com/maps/api/js?key=';
      }
      document.head.appendChild(script);
      /*Get Current location*/
      this.geolocation.getCurrentPosition().then((position) =>  {
          this.location.lat = position.coords.latitude;
          this.location.lng = position.coords.longitude;
      });
      /*Map options*/
      this.mapOptions = {
          center: this.location,
          zoom: 21,
          mapTypeControl: false
      };
      setTimeout(() => {
          this.map = new google.maps.Map(this.mapElement.nativeElement, this.mapOptions);
          /*Marker Options*/
          this.markerOptions.position = this.location;
          this.markerOptions.map = this.map;
          this.markerOptions.title = 'My Location';
          this.marker = new google.maps.Marker(this.markerOptions);
      }, 3000);
  }

}

如果您遇到需要在调用 ngAfterVewInit 挂钩之前访问视图查询结果的情况,我们可以将 static 设置为 true。但是设置为 true 允许从 ngOnInit 生命周期访问视图查询结果。

最新版本Angular,@ViewChild有2个参数

@ViewChild(‘Map’, {static: true}) mapElement: ElementRef;

较新版本的 Angular 要求您提供一个对象作为 @ViewChild 装饰器 (docs) 的第二个参数。该对象需要具有 static.

的布尔值
// {static: boolean}
@ViewChild('Map', {static: false) mapElement: ElementRef;

决定 ifstatic 应该是 true 还是 false 取决于您是否动态呈现模板中的元素,例如 *ngIf*ngFor。如果您不使用这些(或任何其他结构指令),则应将 static 设置为 false 以便您可以尽快访问该元素。

说到何时可以访问元素引用,组件构造函数中有很多逻辑。强烈建议您将其移出构造函数并移至生命周期挂钩中。您绝对需要将任何引用 mapElement 的代码移出构造函数,因为它在那里始终未定义(这可能就是您使用 setTimeout 的原因?)。 {static:false}ElementRef 将在 ngOnInit 中可用,而 {static:true}ElementRef 将在 ngAfterViewInit 中可用。

既然您使用的是 Ionic,那么您也可以看看 their lifecycle hooks