oslew docs
Console
Menu

Delivery planning

A van leaves the depot at nine with a list of orders. The driver needs the stops in a sensible order, a line on a map for each leg, and a time for each door that the customers can be told. Some of the addresses on the list will be wrong, and a stop the geocoder cannot pin to one door is better sent back to the office than driven to.

The approach

  1. Locate each stop with /v1/geocode, and turn away any with no match, a tie, or only a street.
  2. Order them with /v1/optimize: the depot first, a round trip back to it.
  3. Route each leg with /v1/route, for its own distance, time and line, and add the minutes at each door to get arrival times.

Geocoding is address; optimising and routing are routing. They draw on separate buckets, so geocoding the list does not slow the routing. See products and plans.

curl
curl -G "https://api.oslew.com/v1/optimize" \
  -H "Authorization: Bearer $GEO_API_KEY" \
  --data-urlencode 'points=19.4406,-99.2047;19.4326,-99.1332;19.4352,-99.1412;19.3500,-99.1620' \
  --data-urlencode 'geometry=false'
Python
from oslew import Client

# The key is read from GEO_API_KEY.
client = Client(base_url="https://api.oslew.com")

answer = client.optimize(
    "19.4406,-99.2047;19.4326,-99.1332;19.4352,-99.1412;19.3500,-99.1620",
    geometry=False,
)
TypeScript
import { Client } from "@oslew/client";

// The key is read from GEO_API_KEY.
const client = new Client({ baseUrl: "https://api.oslew.com" });

const answer = await client.optimize("19.4406,-99.2047;19.4326,-99.1332;19.4352,-99.1412;19.3500,-99.1620", { geometry: false });
Response
HTTP/1.1 200 OK
content-type: application/json
ratelimit-limit: 100
ratelimit-remaining: 294
ratelimit-reset: 1

{
  "order": [
    0,
    2,
    1,
    3,
    0
  ],
  "waypoints": [
    [
      19.4406,
      -99.2047
    ],
    [
      19.4352,
      -99.1412
    ],
    [
      19.4326,
      -99.1332
    ],
    [
      19.35,
      -99.162
    ],
    [
      19.4406,
      -99.2047
    ]
  ],
  "duration_s": 2173,
  "legs_s": [
    561,
    170,
    651,
    791
  ],
  "nearest_neighbour_s": 2173,
  "distance_m": 34016,
  "geometry": [],
  "engine": "base/hierarchy",
  "provenance": {
    "name": "overture-transportation",
    "release": "2026-08-19.0",
    "license": "ODbL-1.0"
  },
  "took_us": 5137
}

A real response, captured from the service at commit b8f4bde-dirty. Timing fields such as took_us differ on every call.

order is indices into the points you sent, in visiting order; a round trip repeats the start at the end. waypoints are those points in that order, legs_s the time of each leg, andduration_s their sum: 2,173 seconds. nearest_neighbour_s is how long the obvious order — always the closest unvisited stop next — would have taken. Here they are equal: with four points the obvious order is already the best, and for up to eight points the search is exact.

The program

The orders are a list in the program; in yours, they come from wherever orders live. It prints the run with arrival times and writes run.geojson, one line per leg, for a map. Run the TypeScript withnpx tsx delivery.ts; see clients.

Python
"""Plan a delivery run: locate the stops, find the order, route every leg.

    python delivery.py      # writes run.geojson for the driver's map
"""

import json
import sys
import time
from datetime import datetime, timedelta

from oslew import BadRequest, Client, retry_on_rate_limit

client = Client(base_url="https://api.oslew.com")  # the key is read from GEO_API_KEY

DEPOT = "19.4406,-99.2047"
ORDERS = [
    ("ord-101", "Avenida Insurgentes Sur 1602, 03940"),
    ("ord-102", "Paseo de la Reforma 222, 06600"),
    ("ord-103", "Calle Tacuba 1, 06000"),
    ("ord-104", "Calle Que No Existe 99999, 03940"),
]
LEAVE = datetime(2026, 9, 25, 9, 0)  # when the van leaves the depot
AT_EACH_STOP = timedelta(minutes=5)  # parking, stairs, a signature

# 1. Locate every stop. A stop that cannot be pinned to one door is not driven to.
stops, turned_away = [], []
for order_id, address in ORDERS:
    answer = retry_on_rate_limit(client.geocode, address, limit=1)
    top = answer["results"][0] if answer["results"] else None
    if top is None:
        turned_away.append((order_id, address, "no match"))
    elif answer["tied_at_top"] > 1:
        turned_away.append((order_id, address, f"matches {answer['tied_at_top']} places equally well"))
    elif top["precision"] == "street":
        turned_away.append((order_id, address, "found the street, not the door"))
    else:
        stops.append({"id": order_id, "address": top["normalized"]["formatted"],
                      "at": f"{top['lat']},{top['lon']}"})
for order_id, address, why in turned_away:
    print(f"not on this run: {order_id} {address!r}: {why}")
if not stops:
    sys.exit("nothing to deliver")

# 2. The order. Point 0 is the depot, and a round trip starts and ends there.
points = [DEPOT] + [s["at"] for s in stops]
try:
    plan = retry_on_rate_limit(client.optimize, ";".join(points), roundtrip=True, geometry=False)
except BadRequest as e:
    sys.exit(f"cannot plan this run: {e.message}")  # e.g. a stop no road reaches
saved = plan["nearest_neighbour_s"] - plan["duration_s"]
print(f"{plan['duration_s'] / 60:.0f} min of driving; {saved / 60:.0f} min better than nearest-first")

# 3. Route each leg, for its line on the driver's map and its own time.
#    Paced at the routing rate the last answer reported.
rate = (client.rate_limit and client.rate_limit.limit) or 5
clock, total_m, total_s, legs = LEAVE, 0, 0.0, []
for a, b in zip(plan["order"], plan["order"][1:]):
    started = time.monotonic()
    leg = retry_on_rate_limit(client.route, points[a], points[b], geometry=True)
    time.sleep(max(0.0, 1 / rate - (time.monotonic() - started)))
    if not leg["found"]:
        sys.exit(f"no road from {points[a]} to {points[b]}")
    total_m += leg["distance_m"]
    total_s += leg["duration_s"]
    clock += timedelta(seconds=leg["duration_s"])
    name = "depot" if b == 0 else stops[b - 1]["id"]
    print(f"{clock:%H:%M}  {name:8}  {leg['distance_m'] / 1000:5.1f} km  "
          f"{stops[b - 1]['address'] if b else ''}")
    legs.append({
        "type": "Feature",
        "properties": {"to": name, "arrive": f"{clock:%H:%M}",
                       "distance_m": leg["distance_m"], "duration_s": leg["duration_s"]},
        # The service's (lat, lon) pairs, turned into GeoJSON's [lon, lat].
        "geometry": {"type": "LineString", "coordinates": [[lon, lat] for lat, lon in leg["geometry"]]},
    })
    if b != 0:
        clock += AT_EACH_STOP

print(f"{total_m / 1000:.1f} km, {total_s / 60:.0f} min driving, back at {clock:%H:%M}")
with open("run.geojson", "w") as f:
    json.dump({"type": "FeatureCollection", "features": legs}, f)
TypeScript
// Plan a delivery run: locate the stops, find the order, route every leg.
//
//   npx tsx delivery.ts      # writes run.geojson for the driver's map

import { writeFile } from "node:fs/promises";
import { BadRequest, Client, retryOnRateLimit } from "@oslew/client";

const client = new Client({ baseUrl: "https://api.oslew.com" }); // the key is read from GEO_API_KEY

const DEPOT = "19.4406,-99.2047";
const ORDERS: [string, string][] = [
  ["ord-101", "Avenida Insurgentes Sur 1602, 03940"],
  ["ord-102", "Paseo de la Reforma 222, 06600"],
  ["ord-103", "Calle Tacuba 1, 06000"],
  ["ord-104", "Calle Que No Existe 99999, 03940"],
];
const LEAVE = new Date("2026-09-25T09:00:00"); // when the van leaves the depot
const AT_EACH_STOP_S = 5 * 60; // parking, stairs, a signature

const sleep = (ms: number) => new Promise((done) => setTimeout(done, ms));
const hhmm = (d: Date) => d.toTimeString().slice(0, 5);

// 1. Locate every stop. A stop that cannot be pinned to one door is not driven to.
const stops: { id: string; address: string; at: string }[] = [];
for (const [id, address] of ORDERS) {
  const answer = await retryOnRateLimit(() => client.geocode(address, { limit: 1 }));
  const top = answer.results[0];
  let why = "";
  if (!top) why = "no match";
  else if (answer.tied_at_top > 1) why = `matches ${answer.tied_at_top} places equally well`;
  else if (top.precision === "street") why = "found the street, not the door";
  if (why) console.log(`not on this run: ${id} "${address}": ${why}`);
  else stops.push({ id, address: top.normalized.formatted, at: `${top.lat},${top.lon}` });
}
if (stops.length === 0) throw new Error("nothing to deliver");

// 2. The order. Point 0 is the depot, and a round trip starts and ends there.
const points = [DEPOT, ...stops.map((s) => s.at)];
let plan;
try {
  plan = await retryOnRateLimit(() => client.optimize(points.join(";"), { roundtrip: true, geometry: false }));
} catch (e) {
  if (e instanceof BadRequest) throw new Error(`cannot plan this run: ${e.message}`); // e.g. a stop no road reaches
  throw e;
}
const saved = plan.nearest_neighbour_s - plan.duration_s;
console.log(`${(plan.duration_s / 60).toFixed(0)} min of driving; ${(saved / 60).toFixed(0)} min better than nearest-first`);

// 3. Route each leg, for its line on the driver's map and its own time.
//    Paced at the routing rate the last answer reported.
const interval = 1000 / (client.rateLimit?.limit ?? 5);
let clock = new Date(LEAVE);
let totalM = 0;
let totalS = 0;
const legs = [];
for (let i = 0; i + 1 < plan.order.length; i++) {
  const [a, b] = [plan.order[i], plan.order[i + 1]];
  const started = Date.now();
  const leg = await retryOnRateLimit(() => client.route(points[a], points[b], { geometry: true }));
  await sleep(Math.max(0, interval - (Date.now() - started)));
  if (!leg.found || leg.distance_m === null || leg.duration_s === null) {
    throw new Error(`no road from ${points[a]} to ${points[b]}`);
  }
  totalM += leg.distance_m;
  totalS += leg.duration_s;
  clock = new Date(clock.getTime() + leg.duration_s * 1000);
  const name = b === 0 ? "depot" : stops[b - 1].id;
  console.log(`${hhmm(clock)}  ${name.padEnd(8)}  ${(leg.distance_m / 1000).toFixed(1).padStart(5)} km  ${b ? stops[b - 1].address : ""}`);
  legs.push({
    type: "Feature",
    properties: { to: name, arrive: hhmm(clock), distance_m: leg.distance_m, duration_s: leg.duration_s },
    // The service's (lat, lon) pairs, turned into GeoJSON's [lon, lat].
    geometry: { type: "LineString", coordinates: leg.geometry.map(([lat, lon]) => [lon, lat]) },
  });
  if (b !== 0) clock = new Date(clock.getTime() + AT_EACH_STOP_S * 1000);
}

console.log(`${(totalM / 1000).toFixed(1)} km, ${(totalS / 60).toFixed(0)} min driving, back at ${hhmm(clock)}`);
await writeFile("run.geojson", JSON.stringify({ type: "FeatureCollection", features: legs }));

The decisions in it

Which stops to drive to

The geocode saysThe program
No resultsTurns it away: there is nothing to drive to.
tied_at_top > 1Turns it away: the address names several places equally well, and the first is one of them, picked by prominence. A van sent to the wrong one costs more than a phone call.
precision is streetTurns it away: the street is right, the door is unknown, and a long street is kilometres of doors.
rooftop, interpolated, address, poiDrives to it. An interpolated door is placed between two recorded numbers; its precision_m says how far off it can be.

The turned-away list is the useful output for the office: each line says why. A postcode after the last comma is the cheapest way to fewer of them — see getting better accuracy. For a whole day's orders in one go, a batch job with triage does the same sorting at scale.

The order: a round trip, or not

Point 0 is the depot. roundtrip=true, the default, fixes the start there and comes back to it. For a run that ends elsewhere, send roundtrip=false:

  • source=first (the default) still starts at point 0; source=any lets the order start wherever is best — a courier already out.
  • destination=any (the default) ends wherever is best; destination=last ends at the last point you sent — the driver's home, say.

The same four points, starting at the first and ending anywhere

Response
HTTP/1.1 200 OK
content-type: application/json
ratelimit-limit: 100
ratelimit-remaining: 293
ratelimit-reset: 1

{
  "order": [
    0,
    2,
    1,
    3
  ],
  "waypoints": [
    [
      19.4406,
      -99.2047
    ],
    [
      19.4352,
      -99.1412
    ],
    [
      19.4326,
      -99.1332
    ],
    [
      19.35,
      -99.162
    ]
  ],
  "duration_s": 1382,
  "legs_s": [
    561,
    170,
    651
  ],
  "nearest_neighbour_s": 1382,
  "distance_m": 20755,
  "geometry": [],
  "engine": "base/hierarchy",
  "provenance": {
    "name": "overture-transportation",
    "release": "2026-08-19.0",
    "license": "ODbL-1.0"
  },
  "took_us": 4153
}

A real response, captured from the service at commit b8f4bde-dirty. Timing fields such as took_us differ on every call.

Without the return leg the run is 1,382 seconds and ends at point 3. The method is a duration matrix, then nearest neighbour, then 2-opt and Or-opt improvement — exact up to eight points, and good rather than provably best beyond that. Up to 500 points go in one request. Seevisit order.

When a stop cannot be reached from the others — on a piece of road network not joined to the rest — the answer is 400, no order visits every point: some pair is unreachable. The program stops; a kinder one would route the depot to each stop and take out the one whose route comes backfound: false.

Why route every leg again

/v1/optimize can return geometry, but as one line for the whole run, with no mark where one leg ends and the next begins, and one distance for all of it. The driver's map wants a line per leg, and the customers want a time per door. So the program asks for the order without geometry and then routes each leg:

One leg, with its geometry

Response
HTTP/1.1 200 OK
content-type: application/json
ratelimit-limit: 100
ratelimit-remaining: 297
ratelimit-reset: 1

{
  "from": [
    19.4326,
    -99.1332
  ],
  "to": [
    19.4352,
    -99.1412
  ],
  "snapped_from": {
    "from": 355496,
    "to": 355490,
    "frac": 0.16199866758190418,
    "lat": 19.43200133133587,
    "lon": -99.13329035902773,
    "distance_m": 67.23995201279342,
    "time_ds": 110,
    "len_m": 92,
    "two_way": false
  },
  "snapped_to": {
    "from": 289909,
    "to": 289914,
    "frac": 0.6128848307339685,
    "lat": 19.435137788683768,
    "lon": -99.14071924890425,
    "distance_m": 50.883507740291044,
    "time_ds": 35,
    "len_m": 49,
    "two_way": false
  },
  "found": true,
  "distance_m": 1699,
  "duration_s": 208.9,
  "nodes": 28,
  "settled": 78,
  "geometry": [
    [
      19.43200133133587,
      -99.13329035902773
    ],
    [
      19.431903616212214,
      -99.1325623738953
    ],
    [
      19.431911572708522,
      -99.13244027479968
    ],
    [
      19.43171223480434,
      -99.13232577540224
    ],
    [
      19.431627961164846,
      -99.13232788637784
    ],
    [
      19.43085290660703,
      -99.13234781399032
    ]
  ],
  "engine": "base/hierarchy",
  "provenance": {
    "name": "overture-transportation",
    "release": "2026-08-19.0",
    "license": "ODbL-1.0"
  },
  "took_us": 679
}

A real response, captured from the service at commit b8f4bde-dirty. Timing fields such as took_us differ on every call. Shortened for the page: geometry shows 6 of 28.

geometry is (lat, lon) pairs from the snapped start, through every node, to the snapped end; the program turns them into GeoJSON's [lon, lat]. distance_m is whole metres and duration_s seconds. The legs' times differ by seconds from legs_s, because the optimiser times whole seconds between road nodes and a route snaps to the nearest edge; the order was chosen on legs_s, the arrival times come from the routes.

That is one route request per leg, on the routing rate — five a second on the Routing plan — so the loop is paced at the rate the last answer reported, and wrapped in the retry helper.

Arrival times

Departure, plus each leg's duration_s, plus the minutes at each door. Durations are at the posted limit where the data has one and the road class's default speed where it does not, with no traffic: they are free-flow estimates. Tell customers a window, not a minute.

What to watch out for

  • found: false is a 200. A route with no path answers normally, withdistance_m and duration_s null. Check found before adding anything up.
  • A stop far from any road still routes: the ends snap to the nearest road within about 9 km.snapped_to.distance_m says how far that was; a stop hundreds of metres from its road is a walk the time does not include.
  • Two coordinate orders. Points go in as lat,lon and come back as(lat, lon); GeoJSON and most map libraries want [lon, lat]. Seeconventions.
  • Live traffic is an operator feed, on Enterprise. With traffic=live, the optimiser's durations use it but its own legs are routed without it. See live traffic.
  • Road data varies by area. Whether a stop is reachable, and how fast, depends on the road data loaded where it is.

Endpoints

GET/v1/geocodeaddress

Resolve a name, or a number and street, with optional context.

GET/v1/optimizerouting

The fastest order to visit 2 to 500 points: a duration matrix, then nearest-neighbour, 2-opt and Or-opt (exact up to 8 points), with the legs routed.

GET/v1/routerouting

The fastest road route between two points, each snapped to the nearest point on a road.