Google 地图 API; "CORS header ‘Access-Control-Allow-Origin’ missing" 错误

Google Maps API; "CORS header ‘Access-Control-Allow-Origin’ missing" error

我正在尝试使用 Google 地图 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.259947&destinations=25.768915,-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, USA" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "0.9 km",
                  "value" : 881
               },
               "duration" : {
                  "text" : "2 mins",
                  "value" : 144
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

谁能帮我解决这个问题?我在网站上尝试过类似的问题,但未能解决问题。提前致谢。

您正在客户端使用距离矩阵服务。 但是客户端(浏览器)站点不支持您尝试访问 API 的方式,它无法可靠地工作。

很好,有一个适合您的用例的库: 这是 Distance Matrix Service on client side. And here's a vanilla-js example 的指南,请查看。

也许这段代码会对您有所帮助:

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
});