I'm trying to calculate a route between 2 points using google maps directions. When I tried the following code, I got an error:
Access to fetch at 'https://maps.googleapis.com/maps/api/directions/json?destination=31.922007%2C34.768531&mode=driving&origin=32.087001%2C34.8226326&key=MY_KEY' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I saw here: CORS request is not working on google directions API that I cannot use the API this way but I can use the direction service https://developers.google.com/maps/documentation/javascript/directions
import { createClient } from '@google/maps';
import { GOOGLE_GEOCODE_API_KEY } from '../config/keys';
let googleMapsClient;
function initialize() {
googleMapsClient = createClient({key: GOOGLE_GEOCODE_API_KEY});
}
function getGoogleMapsClient() {
if (!googleMapsClient) {
initialize();
}
return googleMapsClient;
}
function calcRoute(origin, destination) {
return getGoogleMapsClient().directions({
origin: origin,
destination: destination,
mode: 'driving',
});
}
As I understand from the documents of the directions service, I must present a map in my app to make the route calculation, but I don't want to. In addition, the documents are dedicated to JS and I'm working with react. How can I make the calculation in react without displaying the map?