Search code examples
angulartypescriptgoogle-mapsgoogle-maps-api-3

@types/google.maps: Cannot find name 'google'


Application just needs zip code input from customers to calculate distances between two points in order to recommend the closest store. No need to display/draw a map. Have a valid Google API Key tested with Postman and a regular Chrome at https://maps.googleapis.com/maps/api/distancematrix/json?. But got CORS using http.get<any>(urlwithparams) from inside application. Found out Google intentionally not allow request from script, have to use its library.

No problem! After reading many posts and Google's Developer Guide, believe I should use DistanceMatrixService and this is the easy sample to follow https://developers.google.com/maps/documentation/javascript/examples/distance-matrix#maps_distance_matrix-typescript

My component .HTML:

<script
      src="https://maps.googleapis.com/maps/api/js?key=KeyValue&callback=clickFind&v=weekly"
      defer
    ></script>

My component .ts:

clickFind()
{
    const map = new google.maps.DistanceMatrixService; <<-- Error: TS2663: Cannot find name 'google'
    ....
}

Result is Cannot find name 'google'. I have tried all the followings,

Cannot find name 'google' angular 8

Google Maps API: No 'Access-Control-Allow-Origin' header is present on the requested resource

Typescript Error Cannot find name 'google' in ionic2 when using googlemaps javascript API

@types/googlemaps/index.d.ts' is not a module

https://www.freakyjolly.com/angular-google-maps-using-agm-core/#more-2316

https://developers.google.com/maps/documentation/distance-matrix/distance-matrix#request-examples

https://www.joshmorony.com/getting-started-with-google-maps-in-ionic-2/

eventually came back to the same

Error: TS2663: Cannot find name 'google'

Summary

  1. @types/googlemaps has been deprecated, if you install it will be told switching over to @types/google.maps even though it still placed @types/googlemaps in package.json, so I ran npm i @types/google.maps --save-dev instead.
  2. The installed version is "@types/google.maps": "^3.51.0"
  3. Many posts above are using early Angular versions up to 9, or axios while mine is Angular v14
  4. @agm/core should not be needed.
  5. Some solutions above build ok but fail at run time for the error.

Solution

  • There could be more than one solution, but here is mine:

    1. npm i -D @types/google.maps

    2. npm i @googlemaps/js-api-loader

    3. no update to tsconfig.app.json, HTML

    4. TS implementation

      const loader = new Loader({apiKey: 'keyvalue'}).load().then( this.test1); test1():void { var gmd = new google.maps.DistanceMatrixService(); gmd.getDistanceMatrix ({ origins: ["jacksonville, fl"], destinations: ["chicago, il", "seattle, wa"], travelMode: google.maps.TravelMode.DRIVING }) .then( (resp) => { ... // do whatever } ); }

    Based on ERROR ReferenceError: google is not defined Angular Map. Thanks to @MrUpsidedown