【发布时间】:2019-08-27 18:26:12
【问题描述】:
我正在尝试将 google maps api 与距离矩阵 api 一起使用,我正在以 json 格式获取路线以及距离和时间。
我从中获取数据的链接示例:
数据查看如下:
{
"destination_addresses" : [ "2920 Zoo Dr, San Diego, CA 92101, USA" ],
"origin_addresses" : [
"San Diego International Airport (SAN), 3225 N Harbor Dr, San Diego, CA 92101, USA"
],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "5.2 mi",
"value" : 8440
},
"duration" : {
"text" : "13 mins",
"value" : 756
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
我在按钮点击 (ajax) 时调用 jquery 函数,如下所示:
$.ajax({
type: 'GET',
url: 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=place_id:' + me.originPlaceId + "&destinations=place_id:" + me.destinationPlaceId + "&key=YOUR_API_KEY&units=imperial",
dataType: "JSONP", // data type expected from server
accepts: 'application/json',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log('Error: ' + error);
}
});
此代码是许多其他帖子的结果,但我仍然收到错误:
SyntaxError: Unexpected token ':'. Parse error.
在 json 数据的第 2 行。 这个错误发生在 safari 浏览器上,如果我在 chrome 上运行代码,我会收到以下错误:
jquery-3.4.1.min.js:2 Cross-Origin Read Blocking (CORB) blocked cross-origin response https://maps.googleapis.com/maps/api/distancematrix/json?origins=place_id:ChIJ7-bxRDmr3oARawtVV_lGLtw&destinations=place_id:ChIJyYB_SZVU2YARR-I1Jjf08F0&key=AYOUR_API_KEY&units=imperial&callback=jQuery34106919863879807548_1566930061936&_=1566930061937 with MIME type application/json.
我需要帮助解决这些错误,提前谢谢你。
【问题讨论】:
-
您是否将
YOUR_API_KEY替换为您的 API 密钥? -
是的,我只是不想公开分享它。
-
为什么你请求的
dataType等于JSONP?真的需要吗? -
是的,因为当它是 JSON 时它给出了 access-control-allow-origin 错误。
标签: javascript jquery json ajax google-distancematrix-api