Reputation: 8137
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.
Upvotes: 1
Views: 965
Reputation: 8137
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.
Upvotes: 3
Reputation: 3872
You can use the object in the ngAfterViewInit event handler. It is fired after the view is loaded.
Upvotes: 0
Reputation: 71961
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
Upvotes: 2