Routing - Vehicle Routing Problem

Problem: split visits across several vehicles so every location is served and total travel distance is minimized.

Show code
import {
  DefaultRoutingSearchParameters,
  FirstSolutionStrategy,
  initRouting,
  RoutingIndexManager,
  RoutingModel,
  setWorkerBridgeEnabled,
} from 'or-tools-wasm/routing';

setWorkerBridgeEnabled(true);
await initRouting();

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 params = DefaultRoutingSearchParameters();
params.firstSolutionStrategy = FirstSolutionStrategy.PATH_CHEAPEST_ARC;
const assignment = await routing.SolveWithParameters(params);
  • 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: