其中,YOUR_API_KEY为你自己的API密钥。
import { Component, OnInit, ViewChild, ElementRef, NgZone } from '@angular/core';
declare var google: any;
@Component({...})
export class MapComponent implements OnInit {
@ViewChild('map') mapElement: ElementRef;
map: any;
...
ngOnInit() {
this.loadMap();
}
loadMap() {
...
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
...
}
}
注:NgZone的引入是为了避免Angular的Change Detection机制和Google Maps API发生冲突。
npm install @types/googlemaps --save-dev
如果还是出现错误,请检查你的API密钥是否正确,或者是否有网络连接问题。
下一篇:Angular地图无法检索数据