i am using directions api with some waypoints. the thing is that its not optimized, it goes with the order of my array and not with the most efficient order. i dont want the order of my array to take part of how the path will be. for example always the api will direct me to the first object on the array, thats not right, it should direct me to, the most efficient.
const destinations = [
{ latitude: 40.962259, longitude: 24.506937,stopover: true },
{ latitude: 37.993381, longitude: 23.713517,stopover: true },
{ latitude: 40.936184, longitude: 24.401282,stopover: true },
// Add more destinations
];
const startingPoint = { latitude: 40.400304, longitude: 23.876982 };
async function planRoute() {
try {
const response = await client.directions({
params: {
origin: `${startingPoint.latitude},${startingPoint.longitude}`,
destination: `${40.397665},${23.884578}`,
waypoints: destinations,
optimizeWaypoints: true,
key: apikey
},
});
if (response) {
// The optimized route is in response.data.routes[0]
const route = response.data.routes[0];
console.log('Optimized route:', route);
}
i tried to change order of the objects on the array and it changed the path of my directions, thats not right.
There are multiple issues with your code
I'm not sure how you even made it work, but first of all, your
waypointsarray is not how it should be formatted in relation to the documentation.Using your format gives me an error:
So I fixed it following the documentation:
Then with this, the code works.
Then passing in the
optimizeWaypointsseems to work fine and is working as intended.Here's a sample snippet for you to verify it yourself using some of your given locations as an example:
If you try changing the
optimizeWaypointstotrueyou will notice that the total distance of the path is significantly reduced. This shows that theoptimizeWaypointsis working as intended. Switching around the waypoint order does not seem to affect it.I hope this helps!