Routing - Simple Routing

Problem: find the shortest route for one vehicle to visit every location and return to the depot.

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: 20 }, () => ({
    x: 52 + Math.random() * 856,
    y: 52 + Math.random() * 516,
  })),
];

const manager = new RoutingIndexManager(locations.length, 1, 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 params = DefaultRoutingSearchParameters();
params.firstSolutionStrategy = FirstSolutionStrategy.PATH_CHEAPEST_ARC;
const assignment = await routing.SolveWithParameters(params);
  • One vehicle starts and ends at the depot.
  • Every customer location must be visited exactly once.
  • The travel cost is the straight-line distance between two locations.
  • Before solving, the map shows the locations without a chosen route.
  • After solving, the route line shows the visit order and return to the depot.

Route

Run the solver to view the route.

Status / Response: