2017-09-06 81 views
1

我嘗試構建基於Angular 2框架的Ionic 2應用程序。 我必須在頁面中顯示地圖。我用這個: https://angular-maps.com/guides/getting-started/Angular 2:多個包含錯誤

它的工作原理很好,但我有這個錯誤在我的控制檯:

You have included the Google Maps API multiple times on this page. This may cause unexpected errors. 

其實,我用幾何谷歌圖書館在一個組件來演算了一些時間旅行。所以,我有我的index.html包含此:

<script src="https://maps.google.com/maps/api/js?sensor=true&key=MYAPIKEY&libraries=geometry"></script> 

如果我刪除,我沒有我的錯誤我在我的地圖頁面,但我不能使用圖書館演算距離我的供應商..

有人可以解釋我如何使用這兩個功能?

我的供應商代碼來演算距離:

//this line doesn't works if I remove my script from my index.html 
let origin = new google.maps.LatLng(user.latitude, user.longitude); 
    let service = new google.maps.DistanceMatrixService(); 
     service.getDistanceMatrix(
      { 
       origins: [origin], 
       destinations: destinations, 
       travelMode: 'DRIVING', 
      }, res =>{ 
       if(res.rows[0]) { 
        for(let i: number = 0; i < res.rows[0].elements.length ; i++) { 
         let element: any = res.rows[0].elements[i]; 
         objects[i].distance = element.distance.text; 
         objects[i].time_travel = element.duration.text; 
        } 
       } 
      }); 

回答

1

由於谷歌地圖API的腳本是由添加' @ agm/core',同時調用map指令,在索引文件中添加maps api reference是多餘的。這是上述錯誤的原因。

所以,請做如下修改

在你的組件

類進口MapsAPILoader

import { AgmCoreModule, MapsAPILoader } from '@agm/core'; 

添加下面的代碼的應用程序組件構造

constructor(private _loader:MapsAPILoader) 
{ 
    _loader.load().then(() => { 
    console.log('google script loaded'); 
}); 

} 

最後從索引中刪除地圖腳本文件。

+0

完成。但是當我的幾何函數被調用時,我保留一個錯誤:Error:Uncaught(在promise中):ReferenceError:google沒有定義 ReferenceError:google沒有定義 –

+0

@ V.Pivet更新了答案。請檢查並讓我知道。 – nikhila

+0

我做了您的修改,我有一次在我的控制檯中登錄。我不再犯我的錯誤了。 –

1

AGM提供了一種方法載入地圖上自己使用MapsAPILoader

import { MapsAPILoader } from '@agm/core'; 
    ... 
    this.mapsLoader.load().then(() => { 
     console.log('maps loaded'); 
    });