Angular 2 (Angular-cli) : Uncaught ReferenceError: google is not defined
Update
Regarding import LatLngBounds = google.maps.LatLngBounds;
I find out that I was calling the custructor (new LatLngBounds()
) before the init of Maps api. In fact, I'm using @agm/core;
. And constructor has to be called after load()
as below
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))); } }); } );}
and I added in my typings.d.ts the following import
import {} from '@types/googlemaps';
Original answer
I solved my problem by having the following config :
1- package.json
"dependencies": { ... "googlemaps": "^1.12.0", ... }
2- tsconfig.json
"types": [ ... "googlemaps" ]
3- And add the google api script in my index.html
<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- In components, use it like below
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;}