12

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"

1
  • 3
    If you're able to compile without issue, you don't have a problem with your @types configuration. Your browser is saying google is not defined. Have you included the scripts that define google globally, and are they loaded before this script is executed? Commented Jan 18, 2019 at 20:31

1 Answer 1

22

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

Sign up to request clarification or add additional context in comments.

2 Comments

looks like @agm/core (newest ver as of 24/07/2021) uses the old types present in the deprecated pkg @types/googlemaps and not the newer one (@types/google.maps). Is there a new reccomended way of embedding g.maps into angular app?
@DuckLing check this one smaillounes.medium.com/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.