在這裏,一步一步的指南,添加一個谷歌地圖組件到angular-cli項目。
第一步:從DefinitelyTyped安裝google.maps:
typings i dt~google.maps --global --save
第二步:如果你已經安裝了舊的分型添加
/// <reference path="../typings/index.d.ts" />
到你的src/typings.d.ts
第3步:生成新組件
ng g component google-maps
下面的代碼添加到:
.TS:
height = '100px';
myLatLng = {lat: -25.363, lng: 131.044};
map:any;
constructor(private googleApi:GoogleApiService) {}
ngOnInit() {
this.googleApi.initMap().then(() => {
let latlng = new google.maps.LatLng(this.myLatLng.lat, this.myLatLng.lng);
this.map = new google.maps.Map(document.getElementById('map'), {
center: latlng,
zoom: 4
});
new google.maps.Marker({
position: latlng,
map: this.map,
title: 'Hello World!'
});
});
}
的.html:
<div id="map" [style.height]="height"></div>
第四步:生成新的服務
ng g service google-maps/shared/google-api
添加GoogleApiService + HTTP_PROVIDERS爲src /main.ts
代碼:
const API_KEY = '[insert your code]';
const url = 'https://maps.googleapis.com/maps/api/js?key='+ API_KEY +'&callback=initMap';
@Injectable()
export class GoogleApiService {
private loadMap: Promise<any>;
constructor(private http:Http) {
this.loadMap = new Promise((resolve) => {
window['initMap'] =() => {
resolve();
};
this.loadScript()
});
}
public initMap():Promise<any> {
return this.loadMap;
}
private loadScript() {
let script = document.createElement('script');
script.src = url;
script.type = 'text/javascript';
if (document.body.contains(script)) {
return;
}
document.getElementsByTagName('head')[0].appendChild(script);
}
}
也許你需要刪除從spec.ts文件的一些線路。 但是,您可以將GoogleMapsComponent添加爲指令。
- 它是超級容易與路線等 擴大也許,如果我有時間我上傳我GoogleMapsComponent的當前版本的github ..