调用谷歌Place Nearby Search API遇CORS错误及语法异常求助
搞定你的两个技术问题:语法错误与Google Maps Places API调用异常
嘿,我来帮你拆解这两个问题——其实它们之间还存在关联呢!
一、先说说Uncaught SyntaxError: Unexpected token :
这个错误的根源其实在你调用Google Maps API的方式上。当你给$.ajax设置dataType: 'jsonp'时,jQuery会默认期望服务器返回JSONP格式的响应——也就是用一个函数调用包裹起来的JSON,比如:
jQuery1234567890({ "html_attributions" : [], "results" : [...] });
但Google Places Nearby Search API返回的是纯JSON(你贴的响应片段就是标准JSON),浏览器会把它当成JavaScript脚本执行,而纯JSON开头的{会直接触发语法解析错误,这就是你看到Unexpected token :的原因。
二、解决Google Maps API的CORS与调用异常
Google Places API 不支持JSONP,所以你用JSONP的路子肯定走不通。要解决CORS问题,有两种靠谱的方案:
方案1:用Google官方的JavaScript SDK(强烈推荐)
Google专门提供了客户端SDK来调用Places服务,不需要自己写AJAX,完全规避CORS问题,还能享受SDK的各种便利。示例代码如下:
// 先确保你在页面里加载了带places库的SDK // <script src="https://maps.googleapis.com/maps/api/js?key=你的API密钥&libraries=places"></script> function searchNearbyRestaurants() { // 创建Places服务实例(用一个空div当容器就行) const service = new google.maps.places.PlacesService(document.createElement('div')); service.nearbySearch({ location: new google.maps.LatLng(city_lat, city_lon), radius: 500, type: ['restaurant'] }, (results, status) => { if (status === google.maps.places.PlacesServiceStatus.OK) { console.log('拿到结果啦:', results); // 这里处理你的业务逻辑 } else { console.error('请求失败:', status); } }); }
这是Google官方推荐的方式,没坑还省心。
方案2:搭个自己的后端代理
如果你非得用AJAX调用,可以在自己的服务器上搭一个代理接口——前端请求自己的代理,再由代理去请求Google的API。这样前端和代理同域,就不会有CORS问题了。
比如用Node.js+Express写个简单代理(示例):
const express = require('express'); const axios = require('axios'); const app = express(); const YOUR_API_KEY = '你的Google API密钥'; app.get('/api/nearby-restaurants', async (req, res) => { const { lat, lon } = req.query; try { const googleResponse = await axios.get(`https://maps.googleapis.com/maps/api/place/nearbysearch/json`, { params: { location: `${lat},${lon}`, radius: 500, type: 'restaurant', key: YOUR_API_KEY } }); res.json(googleResponse.data); } catch (err) { res.status(500).json({ error: '代理请求失败', detail: err.message }); } }); app.listen(3000, () => console.log('代理服务器跑在3000端口啦'));
然后前端的AJAX改成调用自己的代理:
$.ajax({ url:"/api/nearby-restaurants?lat="+city_lat+"&lon="+city_lon, type: "GET", dataType: 'json', cache: false, success: function(response){ console.log('响应结果:', response); } });
最后总结一下
- 你遇到的语法错误,本质是JSONP的响应格式要求和Google API返回的纯JSON不匹配导致的;
- 优先用官方SDK,这是最稳妥的解决方案;
- 非要用AJAX的话,就搭后端代理绕开CORS限制。
内容的提问来源于stack exchange,提问作者I_Tech_Avi
相关产品推荐
相关产品推荐

