google object undefined using angular2-google-maps and googl



我目前正在开发一个使用谷歌地图的angular2应用程序。

我已经使用出色的 sebm angular2-google-maps 模块将谷歌地图的实例嵌入到应用程序中。

我现在遇到的问题是我想使用谷歌地方自动完成搜索栏。

我已将模块导入到我的地图模块中,如下所示:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AgmCoreModule } from 'angular2-google-maps/core';
import { MapComponent } from './map.component';
@NgModule({
imports: [
CommonModule,
AgmCoreModule.forRoot({
apiKey: '************************',
libraries: ['places']
})
],
declarations: [MapComponent]
})
export class MapModule { }

地图本身工作正常。但是,我能找到的所有文档(例如此线程)都说"google"对象现在应该全局存在,并且我应该能够通过简单地在我的组件中声明它来获取它,即

declare var google: any;

当我尝试这样做然后尝试使用谷歌对象时,例如

console.log(google);

。它给了我一个错误,即谷歌是未定义的。

你需要将 MapsAPILoader 注入到你的类中,然后调用 load 方法。

在加载器完成之前,无法访问谷歌对象。

例:

constructor(private _mapsAPILoader: MapsAPILoader) { }

ngAfterViewInit() {
this._mapsAPILoader.load().then(() => {
// Place your code in here...
});
}

这个答案是 amiller29au 通过 github 在这里 - 复制以获得更广泛的访问。

Angular 在加载index.html后运行。如果你在ngOnInit里放了一些东西(最好是ngAfterViewInit),那么document.ready应该已经开火了。

唯一可能出错的方法是,如果您的脚本标签上有获取 google 库的asyncdefer标签。

更好的解决方案是使用node安装谷歌地图,并在需要时设置用于获取谷歌库的任何加载器(使用密钥googlemaps)。然后,您可以在PlacesComponent中放置一个import "googlemaps",以确保库已加载

可以在 ngAfterViewInit 事件处理程序中使用该对象。它在加载视图后触发。

最新更新