After not working with Javascript for a couple of years, I decided to try loading the Google Maps Javascript API npm package in order to display a map and draw directions between two points (Lille and Biarritz, passing through Paris and Bordeaux). Unfortunately, I encountered an error from the Google API with the code UNKNOWN_ERROR and the following message:
A directions request could not be processed due to a server error. The request may succeed if you try again.
Despite attempting multiple times in the past 48 hours, I have been unsuccessful.
config.js
export const API_KEY = 'XXXXXX___A_VALID_GOOGLE_API_KEY_HERE_XXXXXXX'
// the key has access to Directions API & Maps JavaScript API
index.js
import { API_KEY } from './config.js';
import { Loader } from '@googlemaps/js-api-loader';
//////////////////////
// Direction API Test
//////////////////////
const calculateAndDisplayRoute = async function (
directionsService,
directionsRenderer
) {
try {
const google = window.google; // Fix for ESLint Err google is not defined
const res = await directionsService.route({
origin: {
query: 'Lille',
},
destination: {
query: 'Biarritz',
},
waypoints: [
{ location: 'Paris, France' },
{ location: 'Bordeaux, France' },
],
travelMode: google.maps.TravelMode.DRIVING,
avoidTolls: true,
avoidHighways: false,
drivingOptions: {
departureTime: new Date(Date.now()),
trafficModel: 'pessimistic',
},
});
console.log(res);
directionsRenderer.setDirections(res);
} catch (e) {
console.log(`Directions request failed
Code: ${e.code}
Message: ${e.message} `);
}
};
////////////
// API Load
////////////
const init = async function () {
try {
const loader = new Loader({
apiKey: API_KEY,
version: 'weekly',
});
const res = await loader.load();
if (!res) return;
const google = window.google; // Fix for ESLint Err google is not defined
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer();
const map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: { lat: 47, lng: 2 },
});
directionsRenderer.setMap(map);
document
.getElementById('go')
.addEventListener(
'click',
calculateAndDisplayRoute.bind(
this,
directionsService,
directionsRenderer
)
);
} catch (e) {
console.error(e);
}
};
init();
Unfortunately, I have been faced with this strange error and I'm unsure how to resolve it :/
Directions request failed
Code: UNKNOWN_ERROR
Message: DIRECTIONS_ROUTE: UNKNOWN_ERROR:
A directions request could not be processed due to a server error.
The request may succeed if you try again.