参考错误:“谷歌未定义”

Raf*_*fff 12 google-maps typescript typescript-typings angular

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

我需要谷歌地图类型来做这样的事情:

allowedBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(51.130739, -0.868052), // SW
    new google.maps.LatLng(51.891257, 0.559417) // NE
);
Run Code Online (Sandbox Code Playgroud)

所以我做了 npm install --save-dev @typings/googlemaps

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

import {} from 'googlemaps'
declare const google: any; 
Run Code Online (Sandbox Code Playgroud)

在 tsconfig.json 我有"typeRoots": ["node_modules/@types"]和在 tsconfig.app.json"types": ["googlemaps"]

该应用程序编译没有错误,但在 chrome 控制台中我收到一个错误:

ERROR ReferenceError: "google is not defined"

Vad*_*hev 19

这个错误很可能发生allowedBounds 在初始化的那一刻,谷歌地图 API尚未加载,因此谷歌地图对象google.maps.LatLngBounds尚不可用。agm-map附带加载器,它异步加载谷歌地图库。

为了保证谷歌地图API的加载,MapsAPILoader服务可以用作证明如下:

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);
    });
  }

}
Run Code Online (Sandbox Code Playgroud)

这是一个演示,它演示了如何为给定的边界拟合地图