google object undefined using angular2-google-maps and google places searchbar

一个人想着一个人 提交于 2019-12-11 08:28:48

问题


I am currently working on an angular2 application which uses Google Maps.

I have embedded and instance of Google Maps into the app using the excellent sebm angular2-google-maps module.

The problem I now have is that I would like to use the google place autocomplete search bar.

I have imported the module into my map module like this:

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 { }

Which works fine re the map itself. However all the documentation I can find ( for example this thread ) says that the 'google' object should exist globally now and that I should be able to get hold of it by simply declaring it in my component i.e.

declare var google: any;

When I try this though and then try to use the google object e.g.

console.log(google);

... it gives me the error that google is undefined.


回答1:


Angular runs after the index.html has loaded. If you put something in the ngOnInit (better would probably be ngAfterViewInit) then document.ready should already have fired.

The only way this can go wrong is if you have an async or defer tag on your script tag that gets the google library.

An even better solution would be to install google maps using node and set whatever loader you use to get the google library when needed (with the key googlemaps). Then you can place an import "googlemaps" in your PlacesComponent to be sure that the library is loaded




回答2:


You need to inject the MapsAPILoader into your class, then call the load method.

Until the loader is complete the google object will not be accessible.

Example:

constructor(private _mapsAPILoader: MapsAPILoader) { }

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

This answer was curtesy of amiller29au via github here - replicated for wider access.




回答3:


You can use the object in the ngAfterViewInit event handler. It is fired after the view is loaded.



来源:https://stackoverflow.com/questions/41060731/google-object-undefined-using-angular2-google-maps-and-google-places-searchbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!