ReferenceError:“未定义Google”

时间:2019-01-18 19:56:49

标签: angular typescript google-maps typescript-typings

我使用Angular Google Maps在我的angular 7应用程序中显示Google地图。

我需要使用Google Maps键入来完成以下操作:

<decreaseStickerVO>
<taxOfficeCod>04.20</taxOfficeCod>
<vehicleDetailsVOList/>
</decreaseStickerVO>

所以我做了allowedBounds = new google.maps.LatLngBounds( new google.maps.LatLng(51.130739, -0.868052), // SW new google.maps.LatLng(51.891257, 0.559417) // NE );

我尝试了许多不同的方法来尝试解决该错误,但是没有一个对我有用。

npm install --save-dev @typings/googlemaps

在tsconfig.json中,我有import {} from 'googlemaps' declare const google: any; ,在tsconfig.app.json中,"typeRoots": ["node_modules/@types"]

应用程序编译没有错误,但是在chrome控制台中出现错误:

"types": ["googlemaps"]

2 个答案:

答案 0 :(得分:1)

此错误最有可能是因为初始化allowedBounds,尚未加载Google Maps API 的那一刻起出现的,因此google.maps.LatLngBounds之类的Google Maps对象尚不可用。 agm-maploader一起提供,可异步加载Google Maps库

为了确保Google Maps API已加载,可以使用MapsAPILoader service,如下所示:

export class AppComponent  {
  bounds = null;

  constructor(private mapsAPILoader: MapsAPILoader) {
    this.mapsAPILoader.load().then(() => {
      this.bounds = new google.maps.LatLngBounds(
        new google.maps.LatLng(51.130739, -0.868052), // SW
        new google.maps.LatLng(51.891257, 0.559417) // NE
      );
      console.log(this.bounds);
    });
  }

}

Here is a demo展示了如何在给定范围内拟合地图

答案 1 :(得分:0)

尝试重新启动服务器(ng服务)