2016-10-28 4 views
2

私はこの問題について他の回答を確認しましたが、これまでのところ役立たないようです。私はイオン2アプリで地図を表示しようとしています。しかし、#map divを選択しようとすると、undefinedが返されます。私が勘違いしてるのはここのコード@viewChild return undefined

page1.html <div id="map" #mapDiv style="height:380px;"></div>

page1.ts

import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core'; 

import { NavController } from 'ionic-angular'; 

declare var google; 

@Component({ 
    selector: 'page-page1', 
    templateUrl: 'page1.html', 
}) 
export class Page1 implements AfterViewInit { 
    @ViewChild('mapDiv') mapDiv:ElementRef; 
    map; 
    t; 

    constructor(public navCtrl: NavController) { 
    this.initMap(); 
    } 

    ngAfterViewInit(){ 
    console.log('My element: ' + this.mapDiv); 
    } 

    initMap() 
    { 
    this.map = new google.maps.Map(this.mapDiv.nativeElement, { 
        center: new google.maps.LatLng(51.505, -0.09), 
        mapTypeId: google.maps.MapTypeId.ROADMAP, 
        zoom: 11 
       }); 

    this.t = new Date().getTime(); 
     var waqiMapOverlay = new google.maps.ImageMapType({ 
        getTileUrl: function(coord, zoom) { 
          return 'http://tiles.aqicn.org/tiles/usepa-aqi/' + zoom + "/" + coord.x + "/" + coord.y + ".png?token=_TOKEN_ID_"; 
        }, 
        name: "Air Quality", 
     }); 

     this.map.overlayMapTypes.insertAt(0,waqiMapOverlay); 
    } 

} 

コンソールエラー

`Error in ./Page1 class Page1_Host - inline template:0:0 caused by: Cannot read property 'nativeElement' of undefined` 

がある教えてください。 divを選択して、#map div内に地図が表示されるようにします。事前

+0

[Angular 2 @ViewChild注釈の複製が未定義です](http://stackoverflow.com/questions/34947154/angular-2-viewchild-annotation-returns-undefined) – blo0p3r

答えて

4

おかげであなたは、コンストラクタでinitMap()を呼び出します。

@ViewChild('mapDiv') mapDiv:ElementRef;は、ngAfterViewInit()が呼び出される前に初期化されていません。

+1

ありがとうございました。まだ勉強してる。それが私の問題を解決しました。素晴らしい。再度、感謝します。 –