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

使用fetch调用Google Maps Place Search API遭遇CORS错误的解决办法

问题:Google Maps Place Search API 客户端调用出现CORS错误

我有一个项目,需要遍历约300个地点名称,通过Google Maps Place Search API获取这些地点的详情。直接在浏览器中访问替换API_KEY和PLACE_NAME后的API URL时,能正常返回JSON结果,但在HTML的<script>标签中使用fetch调用该API时,出现如下CORS错误:

Access to fetch at 'https://maps.googleapis.com/maps/api/place/textsearch/json?key=API_KEY&query=PLACE_NAME' from origin 'http://localhost:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我对CORS了解甚少,尝试搜索解决方案但大多不适用于我的项目(比如使用require()导入库),或针对其他Google Maps API。且设置为no-cors请求不可行,因为无法获取返回结果。

解决方案

你之前用的是Web Service版本的API调用方式,客户端应该使用Google Maps JavaScript API的Places Library来避免CORS问题,具体步骤如下:

  • 在谷歌云控制台启用Google Maps API。
  • 导入Google Maps JavaScript库:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=callBackFunction"></script>
  • 在另一个<script>标签中编写函数并创建PlacesService实例:
function getLocationData() {
    // PlacesService需要绑定一个div或地图元素,这里创建一个临时元素
    const element = document.createElement('div');

    // 创建PlacesService实例
    const service = new google.maps.places.PlacesService(element);

    // 使用findPlaceFromQuery方法(根据需求选择对应方法)
    service.findPlaceFromQuery(
        // 指定需要返回的字段和查询关键词
        { fields: ['geometry'], query: data[i].name },
        (results) => {
            // 在这里处理返回的结果数据
        })
}

按上述操作即可解决该问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 12:03:16