You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

调用Google Map API时出现CORS错误的技术求助

解决Google Places API调用的CORS错误

这个CORS问题我太熟了!你遇到的请求的资源上不存在'Access-Control-Allow-Origin'标头错误,本质原因是:Google Places的Web服务接口(也就是你用的nearbysearch/json端点)根本不支持浏览器直接发起AJAX请求——它没有配置跨域所需的响应头,所以浏览器会直接拦截这个跨域请求,抛出你看到的错误。

先还原下你的报错信息和代码片段:

请求的资源上不存在'Access-Control-Allow-Origin'标头。

你的前端代码:

$.getJSON( "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + city_lat + "," + city_lon + "&radius=500&type=restaurant&key=AIzaSyC0Lytb6QPHW9NNMwfJva6U4meM9tnvtlk", function(val) { } );

下面给你两个靠谱的解决方案,按推荐程度排序:

方案1:使用Google Maps JavaScript API的Places Library(官方推荐)

这是Google官方为浏览器端设计的使用方式,完全避开CORS问题——因为它内部已经处理了跨域逻辑,不需要你自己发AJAX请求。

步骤:

  1. 先在页面中引入包含Places库的Maps JS API:
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC0Lytb6QPHW9NNMwfJva6U4meM9tnvtlk&libraries=places"></script>
  1. 替换原来的$.getJSON代码,用PlacesService执行附近搜索:
// 创建一个虚拟的地图容器(PlacesService需要绑定到DOM元素,哪怕是隐藏的)
const mapContainer = document.createElement('div');
const map = new google.maps.Map(mapContainer);
const placesService = new google.maps.places.PlacesService(map);

// 构造搜索参数
const searchRequest = {
  location: new google.maps.LatLng(city_lat, city_lon),
  radius: 500,
  type: ['restaurant']
};

// 发起搜索并处理结果
placesService.nearbySearch(searchRequest, (results, status) => {
  if (status === google.maps.places.PlacesServiceStatus.OK) {
    // 这里处理返回的餐厅数据
    console.log('找到的餐厅:', results);
  } else {
    console.error('搜索失败:', status);
  }
});

方案2:通过后端代理请求

如果你不想用Maps JS API,或者有特殊需求,可以搭建一个简单的后端接口,让后端去调用Google的API,再把结果返回给前端——后端请求不受浏览器的CORS限制。

举个Node.js/Express的代理例子:

  1. 后端代码(处理请求转发):
const express = require('express');
const axios = require('axios');
const app = express();

// 允许前端跨域请求(可选,如果你前端和后端不在同一域名下)
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

// 自定义的代理接口
app.get('/api/nearby-restaurants', async (req, res) => {
  const { lat, lon } = req.query;
  const apiKey = 'AIzaSyC0Lytb6QPHW9NNMwfJva6U4meM9tnvtlk';
  const googleApiUrl = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${lat},${lon}&radius=500&type=restaurant&key=${apiKey}`;

  try {
    const response = await axios.get(googleApiUrl);
    res.json(response.data);
  } catch (error) {
    res.status(500).json({ error: '请求Google API失败' });
  }
});

app.listen(3000, () => console.log('代理服务器运行在http://localhost:3000'));
  1. 前端修改后的代码:
$.getJSON(`http://localhost:3000/api/nearby-restaurants?lat=${city_lat}&lon=${city_lon}`, function(val) {
  // 处理返回的餐厅数据
});

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

火山引擎 最新活动