Loading solver…
Routing - Vehicle Routing Problem
Problem: split visits across several vehicles so every location is served and total travel distance is minimized.
Show code
import {
FirstSolutionStrategy,
RoutingIndexManager,
RoutingModel,
} from 'or-tools-wasm/routing';
const locations = [
{ x: 480, y: 310 },
...Array.from({ length: 60 }, () => ({
x: 46 + Math.random() * 868,
y: 70 + Math.random() * 496,
})),
];
const manager = new RoutingIndexManager(locations.length, 4, 0);
const routing = new RoutingModel(manager);
const transit = routing.registerTransitCallback((from, to) => {
const a = locations[manager.indexToNode(from)];
const b = locations[manager.indexToNode(to)];
return Math.round(Math.hypot(a.x - b.x, a.y - b.y));
});
routing.setArcCostEvaluatorOfAllVehicles(transit);
const demand = routing.registerUnaryTransitCallback((from) =>
manager.indexToNode(from) === 0 ? 0 : 1,
);
routing.addDimensionWithVehicleCapacity(
demand,
0,
Array(4).fill(Math.ceil((locations.length - 1) / 4)),
true,
'load',
);
const result = await routing.solve({
firstSolutionStrategy: FirstSolutionStrategy.PATH_CHEAPEST_ARC,
executor: 'worker',
});
console.log(result.status, result.assignment?.objectiveValue());
- Several vehicles start and end at the same depot.
- Every destination must be assigned to exactly one vehicle route.
- Each destination has demand 1, and each vehicle has a balanced destination capacity.
- The travel cost is the straight-line distance between two locations.
- The solver minimizes total distance across all vehicle routes.
- Before solving, the map shows unassigned destinations; after solving, each color is one vehicle route.
Routes
Run the solver to view vehicle routes.
Status / Response: