Angular 2 (Angular-cli) : Uncaught ReferenceError: google is not defined

Angular 2 (Angular-cli) : Uncaught ReferenceError: google is not defined

我已经努力了几个小时,试图在我的 Angular 2 项目中使用 googlemaps PlaceResult Angular-cli.

我必须使用@types 安装 googlemaps 并将其添加到我的 tsconfig.json 配置文件的 "types" 属性下。

{
    ...
    "types": [
      "google-maps"
    ]
  }
}

我成功地在我的 Angular 2 组件中使用了 google.maps.places.PlaceResult,只需导入它!

import { ActivatedRoute, Params } from "@angular/router";
import { MapsAPILoader } from "angular2-google-maps/core";

import PlaceResult = google.maps.places.PlaceResult;
import GeocoderRequest = google.maps.GeocoderRequest;
...

几个小时后,我不得不使用 google.maps.Marker,它与 PlaceResultGeocoderRequest 在同一个定义文件中。所以我简单地将其导入如下:

[Line 12] import PlaceResult = google.maps.places.PlaceResult;
[Line 13] import GeocoderRequest = google.maps.GeocoderRequest;
[Line 14] import Marker = google.maps.Marker;
[Line 15] import LatLng = google.maps.LatLng;
...

但我在运行时遇到意外错误

Uncaught ReferenceError: google is not defined    search.component.ts:14
at Object.444 (search.component.ts:14)
at __webpack_require__ (bootstrap 26c2b97…:52)
at Object.727 (app.config.ts:11)
at __webpack_require__ (bootstrap 26c2b97…:52)
at Object.602 (src async:7)
at __webpack_require__ (bootstrap 26c2b97…:52)
at Object.1258 (.*$:7)
at __webpack_require__ (bootstrap 26c2b97…:52)
at webpackJsonpCallback (bootstrap 26c2b97…:23)
at main.bundle.js:1    

请注意,webpack 在我的组件的 行 14 处抛出此错误。这意味着(如果我错了请纠正我)前面几行(使用相同的"google")效果很好。

我是不是漏掉了什么?


我使用:

更新

关于导入 LatLngBounds = google.maps.LatLngBounds; 我发现我在 Maps api 初始化之前调用了 custructor (new LatLngBounds())。事实上,我正在使用 @agm/core;。并且必须在 load() 之后调用构造函数,如下所示

ngOnInit() {
    this.mapsAPILoader.load().then(() => {

                    this.page$.subscribe(page => {
                        if (page && page.content) {
                            this.latLngBounds = new google.maps.LatLngBounds();

                            page.content.forEach(w => this.latLngBounds.extend(new google.maps.LatLng(lat, lng)));
                        }
                    });

                }
            );
}

并且我在 typings.d.ts 中添加了以下导入

import {} from '@types/googlemaps';

原回答

我通过以下配置解决了我的问题:

1- package.json

"dependencies": {
    ...
    "googlemaps": "^1.12.0",
    ...
  }

2- tsconfig.json

"types": [
      ...
      "googlemaps"
    ]

3- 并在我的 index.html

中添加 google api 脚本
<head>
    ...
</head>
<body>
   <app-root>Loading...</app-root>

   <script src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places&language=fr" async defer></script>
</body>
</html> 

4- 在组件中,像下面这样使用它

declare var google: any;

@Component({
    ...
})
export class SearchComponent implements OnInit, AfterViewInit {

    // Google Maps
    bounds: google.maps.LatLngBounds;
    markers: google.maps.Marker[];
    infoWindow: google.maps.InfoWindow;

}