首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >TypeError:无法读取未定义的Ionic-v4的属性“nativeElement”

TypeError:无法读取未定义的Ionic-v4的属性“nativeElement”
EN

Stack Overflow用户
提问于 2019-09-09 10:46:49
回答 2查看 1.8K关注 0票数 1

我正在尝试这个示例,在这个例子中,步骤6获得一个错误。我尝试了几种解决方案,但这些方法都行不通。

page.ts

代码语言:javascript
运行
复制
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { PlaceDataService } from '../services/place-data.service';
declare var google: any;

@Component({
  selector: 'app-add-marker',
  templateUrl: './add-marker.page.html',
  styleUrls: ['./add-marker.page.scss'],
})
export class AddMarkerPage implements OnInit {

  @ViewChild('map', {static: false}) mapContainer: ElementRef;
  map: any;
  museumData = [];

  constructor(
    private geolocation: Geolocation,
    private placeDataService: PlaceDataService) { }

  ngOnInit() {
    this.museumData = this.placeDataService.getMuseums();
    this.displayGoogleMap();
    this.getMarkers();
  }

  displayGoogleMap() {
    const latLng = new google.maps.LatLng(28.6117993, 77.2194934);

    const mapOptions = {
      center: latLng,
      disableDefaultUI: true,
      zoom: 4,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    this.map = new google.maps.Map(this.mapContainer.nativeElement, mapOptions);
  }

  getMarkers() {
    // tslint:disable-next-line:variable-name
    for (let _i = 0; _i < this.museumData.length; _i++) {
      if (_i > 0) {
        this.addMarkersToMap(this.museumData[_i]);
      }
    }
  }

  addMarkersToMap(museum) {
    const position = new google.maps.LatLng(museum.latitude, museum.longitude);
    const museumMarker = new google.maps.Marker({ position, title: museum.name });
    museumMarker.setMap(this.map);
  }

}

page.html

代码语言:javascript
运行
复制
<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-back-button></ion-back-button>
    </ion-buttons>
    <ion-title>Museum in India</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content class="ion-padding">
  <div #map id="map"></div>
</ion-content>

请帮帮忙

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-09-09 13:57:03

您应该在这里标记“真”静态:

@ViewChild('map',{静态: false}) mapContainer: ElementRef;

在此之后,您的代码将运行良好。

它将是:

@ViewChild('map',{静态: true}) mapContainer: ElementRef;

票数 3
EN

Stack Overflow用户

发布于 2021-05-13 12:11:04

对我来说,问题在于我试图在构造函数中引用本机。我使用的是离子5,但与4相同。将代码移到ionViewDidEnter()中,使用静态:false解决它。对你们来说,解决办法是:

代码语言:javascript
运行
复制
ngOnInit() {
    
}
ionViewDidEnter(){
   this.museumData = this.placeDataService.getMuseums();
   this.displayGoogleMap();
   this.getMarkers();
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57852460

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档