Rafff
Rafff

Reputation: 1518

ReferenceError: "google is not defined"

I use Angular Google Maps to display a google map in my angular 7 app.

I needed google maps typings to do something like this:

allowedBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(51.130739, -0.868052), // SW
    new google.maps.LatLng(51.891257, 0.559417) // NE
);

So I did npm install --save-dev @typings/googlemaps

I tried many different things to try to resolve the error but none worked for me.

import {} from 'googlemaps'
declare const google: any; 

In tsconfig.json I have "typeRoots": ["node_modules/@types"] and in tsconfig.app.json "types": ["googlemaps"]

The app compiles without errors but in chrome console I get an error:

ERROR ReferenceError: "google is not defined"

Upvotes: 12

Views: 17324

Answers (1)

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59328

This error most likely occurs since the moment when allowedBounds is getting initialized, Google Maps API is not yet loaded and therefore Google Maps objects like google.maps.LatLngBounds are not yet available. agm-map ships with loader which loads Google Maps library asynchronously.

In order to ensure Google Maps API is loaded, MapsAPILoader service could be utilized as demonstrated below:

export class AppComponent  {
  bounds = null;

  constructor(private mapsAPILoader: MapsAPILoader) {
    this.mapsAPILoader.load().then(() => {
      this.bounds = new google.maps.LatLngBounds(
        new google.maps.LatLng(51.130739, -0.868052), // SW
        new google.maps.LatLng(51.891257, 0.559417) // NE
      );
      console.log(this.bounds);
    });
  }

}

Here is a demo which demonstrates how to fit a map for a given bounds

Upvotes: 22

Related Questions