Search code examples
angulargoogle-mapsgoogle-placesangular-google-maps

How to fix type error in Angular Google Maps?


I am using Angular Google Maps in my app, but I cannot use google.maps.places.PlaceResult as a type for an important variable in my code.


I am implementing this code: (Scroll down to Add Location/Places Search bar)

https://www.freakyjolly.com/angular-7-6-add-google-maps-in-angular-2-plus-applications-using-angular-google-maps-module-agm-core-easily/

I am doing a places search on the map, and I am getting this error:

enter image description here

In this code:

ngOnInit() {
    // Load places autocomplete
    this.maps.load().then(() => {
      this.setCurrentLocation();
      this.geoCoder = new google.maps.geoCoder;

      let autocomplete = new google.maps.places.autocomplete(this.searchElementRef.nativeElement, {
        types: ["address"]
      });

      autocomplete.addListener("place_changed", () => {
        this.ngZone.run(() => {
          // Get the place result
          let place: google.maps.places.PlaceResult = autocomplete.getPlace();

          // Verify result
          if (place.geometry === undefined || place.geometry === null) {
            return;
          }

          // Set latitude, longitude & zoom
          this.userLat = place.geometry.location.lat();
          this.userLng = place.geometry.location.lng();
          this.zoom = 12;
        });
      });
    });
  }

I am just following the example, but it seems to not recognize google. How do you fix this?

I expect to use the example in the link as it is, but I cannot.

Thanks in advance!


Solution

  • To fix this issue, you need to add a file called, google-maps.d.ts in your root folder inside a folder called types.

    Then in that file add the following code:

    google-maps.d.ts

    import '@types/googlemaps';
    
    declare global {
        interface Window {
            google: typeof google;
        }
    }
    

    This will allow you to give variables a type in typescript, of type google.X.X. Make sure you have types installed into your project, npm install --save @types/googlemaps.

    Also, make sure you add types in your tsconfig.json file to point it the folder with the code:

    tsconfig.json

    // tsconfig.json
    compilerOptions: {
       ...
       "typeRoots": [
         "node_modules/@types",
         "types"
       ],
       ...
    }
    

    Where I got the answer from, (Scroll down to the second answer by feilxmosh):

    How to install Typescript typings for google maps

    Credit goes to @JensHabegger for sending me this link. I answered my own question because JensHabegger did not.