问题描述
您正在客户端使用距离矩阵服务。 客户端(浏览器)站点不支持您尝试访问API的方式,并且这种方式无法可靠地工作。
这是客户端上的Distance Matrix Service指南。这是一个vanilla- js示例,请检查一下。
也许此片段将帮助您:
const matrix = new google.maps.distanceMatrixService();
matrix.getdistanceMatrix({
origins: [new google.maps.LatLng(25.7694708, -80.259947)],
destinations: [new google.maps.LatLng(25.768915, -80.254659)],
travelMode: google.maps.TravelMode.DRIVING,
}, function(response, status) {
//do something
});
解决方法
我正在尝试使用Google Maps API计算两个地方之间的预计旅行时间。我通过以下方式要求数据:
const Url = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=25.7694708,-80.259947&destinations=25.768915,-80.254659&key=' + API_KEY;
try {
const response = await fetch(Url);
console.log(response);
const data = await response.json();
console.log(data.rows);
} catch(e){
console.log(e);
}
问题是在浏览器控制台中出现错误:
TypeError: NetworkError when attempting to fetch resource
它也向我显示警告:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://maps.googleapis.com/maps/api/distancematrix/json?origins=25.7694708,-80.254659&key=API_KEY. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
但是,当我查看网络部分中的控制台时,它显示呼叫成功完成,并且显示以下json:
{
"destination_addresses" : [ "3670 SW 3rd St,Miami,FL 33135,USA" ],"origin_addresses" : [ "3911 SW 2nd Terrace,Coral Gables,FL 33134,"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "0.9 km","value" : 881
},"duration" : {
"text" : "2 mins","value" : 144
},"status" : "OK"
}
]
}
],"status" : "OK"
}
有人可以帮我解决这个问题吗?我已经在网站上尝试过类似的问题,但无法解决问题。提前致谢。