I am trying to use Google Routes API, however it is returning a 404 error. No information on the network tab or anywhere else gives any indication of why this is happening so it is almost impossible to troubleshoot.
Why might a 404 error be occurring?
The same API Key worked perfectly fine with Directions Matrix API.
Here is the request below, if you see something wrong, please let us know:
// Set up the Routes API endpoint and the API key
const apiKey = 'xxx'; // Replace with your actual API key
const routesApiUrl = `https://routes.googleapis.com/v2:computeRoutes?key=${apiKey}`;
const directionsTo = $mapElement.data('map-directions-destination');
$('.directions__form').on('submit', function (e) {
e.preventDefault();
const directionsFrom = jQuery.trim(jQuery('.directions__postcode').val());
const requestBody = {
origins: [`${directionsFrom}`], // Origin
destinations: [`${directionsTo}`], // Destination
travelMode: 'DRIVE', // Can be 'DRIVE', 'WALK', 'BICYCLE', etc.
routingPreference: 'TRAFFIC_AWARE', // Optional, use 'TRAFFIC_AWARE' to consider traffic
unitSystem: 'IMPERIAL', // Optional, specify unit system (e.g., 'IMPERIAL' or 'METRIC')
};
// Send the request to the Routes API using fetch
fetch(routesApiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "DELETE, POST, GET, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization, X-Requested-With"
},
body: JSON.stringify(requestBody)
})
.then(response => response.json())
.then(data => {
if (data.routes && data.routes.length > 0) {
const route = data.routes[0]; // Assuming the first route
// Prepare data for rendering the directions
const duration = route.legs[0].duration;
const distance = route.legs[0].distance;
// Optionally, you can create a new marker on the map or process the route data
marker.setMap(null); // Remove the existing marker (if any)
// Render the directions panel or display turn-by-turn directions
const directionsPanel = $('.directions__turn-by-turn').get(0);
directionsPanel.innerHTML = `
<div>
<h3>Duration: ${duration.text}</h3>
<p>Distance: ${distance.text}</p>
<h4>Directions:</h4>
<ul>
${route.legs[0].steps.map(step => `<li>${step.html_instructions}</li>`).join('')}
</ul>
</div>
`;
// Optional: Render the route on the map (if desired)
// Example: You could use a polyline or map markers to show the route visually
const routePath = route.legs[0].steps.map(step => step.polyline);
const polyline = new google.maps.Polyline({
path: routePath, // A simplified example; you can refine this based on your actual data
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
polyline.setMap(map);
}
})
.catch(error => {
console.error('Error fetching Routes API:', error);
});
});
Here is a screenshot of the response:
I have made a reproducible example here - the API keys have been taken out.
https://codepen.io/JuliusGoddard/pen/emOGzpZ
I note that there are very few questions related to Routes API and documentation is scarce.
Furthermore, support for Directions Matrix API runs out on 1 March 2025, therefore many projects are going to lose their map functionality, resulting in many developers facing [problems within the next few months when they inevitably have to migrate from Directions Matrix API to Routes API.
There are multiple differences between:
The latter of which you are now trying to use.
It is not clear which API you were using as you state:
The same API Key worked perfectly fine with Directions Matrix API.
However, there is no Directions Matrix API
Based on your current requestBody
you are sending some parameters associated with the Distance Matrix API request and response. For example, the destinations
and origins
parameters are arrays and are specific to that API and will be ignored/rejected by one of the two Routes API REST services.
In contrast the computeRoutes endpoint of the Routes API accepts parameters such as origin
and destination
and are single Waypoint objects that contain a Location object.
You might want to have a look at the computeRouteMatrix endpoint as that does accept the parameters of your current requestBody
but for now I will assume you want to target the computeRoutes
service.
Firstly you need to update your routesApiUrl
to the correct endpoint:
const routesApiUrl = `https://routes.googleapis.com/directions/v2:computeRoutes?key=${apiKey}`;
Secondly, you need to send the correct body with correct parameters. Here is an example of how they should look:
const requestBody = {
origin:{
location:{
latLng:{
latitude: 37.419734,
longitude: -122.0827784
}
}
},
destination:{
location:{
latLng:{
latitude: 37.417670,
longitude: -122.079595
}
}
},
travelMode: "DRIVE",
routingPreference: "TRAFFIC_AWARE",
computeAlternativeRoutes: false,
routeModifiers: {
avoidTolls: false,
avoidHighways: false,
avoidFerries: false
},
languageCode: "en-US",
units: "IMPERIAL"
}
Thirdly, please refer to the Migrate from Directions API or Distance Matrix API help pages as you will also need to refactor what you do with the directionsFrom
and directionsTo
variables in your code as these look to be extracting values from your application. There is a good section on Request parameter conversions and Update the REST API endpoints to help you migrate.
Lastly, and to answer your actual question, I believe the 404
is because there is no https://routes.googleapis.com/v2:computeRoutes
route. It's https://routes.googleapis.com/directions/v2:computeRoutes
as per my first point.