@types/google.maps:找不到名称“google”

问题描述 投票:0回答:1

应用程序只需要客户输入邮政编码即可计算两点之间的距离,以推荐最近的商店。无需显示/绘制地图。使用 Postman 和常规 Chrome 在

https://maps.googleapis.com/maps/api/distancematrix/json?
测试有效的 Google API 密钥。但从内部应用程序中使用
http.get<any>(urlwithparams)
获得了 CORS。发现Google故意不允许来自脚本的请求,必须使用它的库。

没问题!在阅读了许多帖子和 Google 的开发人员指南后,相信我应该使用

DistanceMatrixService
,这是易于遵循的示例 https://developers.google.com/maps/documentation/javascript/examples/distance-matrix#maps_distance_matrix-typescript

我的组件.HTML:

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

我的组件.ts:

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

结果是

Cannot find name 'google'
我已尝试以下所有方法

找不到名称“google”角8

Google 地图 API:请求的资源上不存在“Access-Control-Allow-Origin”标头

使用 googlemaps javascript API 时,打字稿错误无法在 ionic2 中找到名称“google”

@types/googlemaps/index.d.ts'不是模块

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/

最终又回到原来的样子

错误:TS2663:找不到名称“google”

总结

  1. @types/googlemaps
    已被弃用,如果您安装它,即使它仍然将
    @types/google.maps
    放在 package.json 中,也会被告知切换到
    @types/googlemaps
    ,所以我改为运行
    npm i @types/google.maps --save-dev
  2. 安装的版本是
    "@types/google.maps": "^3.51.0"
  3. 上面的许多帖子都使用 Angular 9 之前的早期版本,或者
    axios
    ,而我的是 Angular v14
  4. @agm/core
    应该不需要。
  5. 上面的一些解决方案构建正常,但在运行时因错误而失败。
angular typescript google-maps google-maps-api-3
1个回答
1
投票

可能有不止一种解决方案,但这是我的:

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

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

  3. 没有更新tsconfig.app.jsonHTML

  4. TS实施

    const loader = new Loader({apiKey: 'keyvalue'}).load().then( this.test1); 测试1():无效 { var gmd = new google.maps.DistanceMatrixService(); gmd.getDistanceMatrix ({ 出发地:[“佛罗里达州杰克逊维尔”],目的地:[“伊利诺伊州芝加哥”,“华盛顿州西雅图”],travelMode:google.maps.TravelMode.DRIVING }) 。然后( (分别)=> { ... // 做任何事 } ); }

基于ERROR ReferenceError:google未定义Angular Map。感谢@MrUpsidedown

© www.soinside.com 2019 - 2024. All rights reserved.