Ionic 2 Google Maps :: Uncaught(承诺):TypeError:无法读取null的属性'firstChild'

时间:2017-10-10 07:53:21

标签: google-maps cordova ionic2

我正在使用离子2并尝试使用其JS API加载谷歌地图。 这是我的代码:

import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController, Platform, NavParams } from 'ionic-angular';
declare var google;

@Component({
  selector: 'page-map',
  templateUrl: 'map.html',
})
export class MapPage {

  @ViewChild('map') mapElement: ElementRef;
  map: any;
  latitude : any;
  longitude : any;

  constructor(public platform: Platform, public navCtrl: NavController,public navParams: NavParams) {   

    this.platform = platform;    
    this.initializeMap();
  }

  ionViewDidLoad(){
    this.initializeMap();
  }  

  initializeMap() {    
       this.platform.ready().then(() => {
       var minZoomLevel = 12;

       this.map = new google.maps.Map(document.getElementById('map'), {
           zoom: minZoomLevel,
           center: new google.maps.LatLng(38.50, -90.50),
           mapTypeId: google.maps.MapTypeId.ROADMAP
       });

       var position = new google.maps.LatLng("23.032612699999998", "72.56187790000001");
       var dogwalkMarker = new google.maps.Marker({position: position, title: "Testing"});
       dogwalkMarker.setMap(this.map);
   });

   } 

}

我还在cordova.js之前在index.html文件中添加了JS的引用:

<script src="http://maps.google.com/maps/api/js"></script>

这是我的HTML:

<ion-header>
  <ion-navbar hideBackButton side="left">  
    <ion-title  style="margin-left: 0px;"><span class="menuTitle">Map</span></ion-title>    
  </ion-navbar>

 </ion-header>

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

代码不会显示任何错误,但是当我尝试加载此页面时,它会显示如下错误:

未捕获(承诺):TypeError:无法读取属性'firstChild'为null

1 个答案:

答案 0 :(得分:2)

使用mapElement

打字稿文件

let minZoomLevel = 12;
let mapOptions = {
   zoom: minZoomLevel,
   center: new google.maps.LatLng(38.50, -90.50),
   mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);