javascriptreactjsfetch-apigoogle-distancematrix-api

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


I'm trying to calculate the estimated travel time between two places, with the Google Maps API. I am asking for the data in the following way:

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

The problem is that in the browser console I get the error:

TypeError: NetworkError when attempting to fetch resource

and it also shows me a warning:

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).

But when I look at the console in the network part it shows me that the call was completed successfully and it shows me the following 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"
}

Can someone help me solve this problem? I have tried similar questions on the site but I have not been able to solve the problem. Thanks in advance.


Solution

  • You are using Distance Matrix Service on client side. But the manner you trying to access the API is not supported for client(browser)-site and it will not work reliably.

    Good that there is a library for your use-case: Here's the guide for the Distance Matrix Service on client side. And here's a vanilla-js example Check it out.

    Maybe this snippet will help you:

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