Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"

like image 987
Rafff Avatar asked Jan 18 '19 19:01

Rafff


People also ask

How do you fix Google is not defined?

In summary, it's always caused by trying to use the Google Maps API (or some other Google API) before it's loaded. This can be fixed by either changing up the import order, using something like jQuery to run your code after the whole page has loaded, or by making sure your browser isn't the problem.

Why this page can't load Google Maps correctly?

Unless a valid API key is present, the map will be displayed in a lower resolution and will have a watermark on it. If the credit card linked to the account is invalid or the number of free map views is surpassed, the "This Page Can't Load Google Maps Correctly" error will show up.

Where do I get Google Map API key?

Go to the Google Maps Platform > Credentials page. On the Credentials page, click Create credentials > API key. The API key created dialog displays your newly created API key.


1 Answers

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

like image 149
Vadim Gremyachev Avatar answered Sep 21 '22 22:09

Vadim Gremyachev