2016-06-14 39 views
4

我正在嘗試將googlemaps實施到我的angular-cli項目。我知道有一個'angular2-google-maps'組件(github),但我需要路由和更多自定義功能。將googlemaps添加到angular-cli

我發現執行地圖到一個項目有兩種方式:

1:stackoverflow:與谷歌API載入 - 但我無法弄清楚如何初始化谷歌,地圖...

2:使用DefinitelyTyped google.maps.d.ts。 我將它與--global(因爲環境ist棄用..)安裝到我的項目,並將index.d.ts(全球)添加到src/typings.d.ts,並可以使用「google.map ..」在.TS文件:

myLatLng = {lat: -25.363, lng: 131.044}; 
    map:any; 

    constructor() { 
    this.map = new google.maps.Map(document.getElementById('map'), { 
     center: this.myLatLng, 
     zoom: 4 
    }); 
    } 

但如果我有角CLI它的錯誤構建它: 「的ReferenceError:谷歌沒有定義」

什麼想法?

回答

6

在這裏,一步一步的指南,添加一個谷歌地圖組件到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 ..