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
@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."@types/google.maps": "^3.51.0"
axios
while mine is Angular v14@agm/core
should not be needed.There could be more than one solution, but here is mine:
npm i -D @types/google.maps
npm i @googlemaps/js-api-loader
no update to tsconfig.app.json, HTML
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