You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular14使用@types/google.maps报错:TS2663: Cannot find name 'google'

解决方案:Angular14中正确集成Google Distance Matrix Service

一、调整脚本加载方式

别直接在组件HTML里插Google Maps脚本,组件加载时脚本可能还没就绪,而且TS编译时识别不了全局变量。直接在angular.json的scripts数组里配置,确保全局生效:

"scripts": [
  "https://maps.googleapis.com/maps/api/js?key=你的API密钥"
]

二、让TypeScript识别google全局变量

装了@types/google.maps后,还得给TS明确类型配置:

  1. 确认依赖安装到位:
npm install @types/google.maps --save-dev
  1. 在tsconfig.json的compilerOptions.types里添加类型声明:
"compilerOptions": {
  // 其他原有配置...
  "types": [
    "google.maps"
  ]
}
  1. 如果还是报错,在组件顶部手动声明全局变量兜底:
declare var google: typeof google.maps;

三、确保服务实例化时机正确

Angular组件初始化时,Google脚本可能还没加载完,别在ngOnInit里直接实例化,先判断脚本状态:

clickFind() {
  // 先检查Google服务是否就绪
  if (!window.google?.maps?.DistanceMatrixService) {
    console.error('Google Maps脚本还没加载好');
    return;
  }

  const distanceService = new google.maps.DistanceMatrixService();
  distanceService.getDistanceMatrix({
    origins: ['用户输入的邮编'],
    destinations: ['门店1邮编', '门店2邮编'],
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.METRIC
  }, (response, status) => {
    if (status === google.maps.DistanceMatrixStatus.OK) {
      // 在这里处理返回的距离数据,筛选最近门店
      console.log(response);
    } else {
      console.error('请求失败:', status);
    }
  });
}

四、备选方案:后端代理绕开CORS

要是前端集成还是有问题,干脆把请求放后端做:自己写个后端接口,前端调用这个接口,由后端去请求Google的API,完全避开前端的CORS和脚本集成问题。比如Node.js后端示例:

const axios = require('axios');
app.get('/api/get-distance', async (req, res) => {
  const { origin, destinations, apiKey } = req.query;
  const googleApiUrl = `https://maps.googleapis.com/maps/api/distancematrix/json?origins=${origin}&destinations=${destinations}&key=${apiKey}`;
  try {
    const result = await axios.get(googleApiUrl);
    res.json(result.data);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

前端直接调用自己的/api/get-distance接口就行,不用管CORS。


内容的提问来源于stack exchange,提问作者Jeb50

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 23:55:18