oslew docs
Console
Menu

Cleaning GPS traces

A fleet's trackers report a position every few seconds. The raw trace wanders off the road by a few metres, jumps somewhere absurd when a receiver loses the sky, and goes quiet in car parks. You want, per trip, the distance driven on roads and the minutes spent above the posted limit — numbers you could put in front of a driver.

The approach

  1. Cut trips. Group the fixes by vehicle, sort them by time, and start a new trip wherever ten minutes pass without one.
  2. Match each trip to the roads with POST /v1/match, in requests of at most 10,000 points, each after the first starting on the last fix of the one before.
  3. Measure. The answer's distance_m is the distance along the matched roads; its per-point positions and speed_limits_kmh, with your own timestamps, give speeds against limits.
  4. A trip of one fix is not a path. /v1/snap says which road it was beside.

Both are the routing product, and a request takes one token whatever its size: a 10,000-point trace costs the same as one fix. See rate limits.

A real answer to a two-minute trace of 25 fixes

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

{
  "points": [
    {
      "lat": 19.419265833691888,
      "lon": -99.1793149055659,
      "from": 362390,
      "to": 362686,
      "along": 0.16342062635322144,
      "distance_m": 2.6727302657997343
    },
    {
      "lat": 19.418717279588495,
      "lon": -99.1795863931191,
      "from": 362686,
      "to": 362687,
      "along": 0,
      "distance_m": 12.590083383713226
    },
    {
      "lat": 19.418717279588495,
      "lon": -99.1795863931191,
      "from": 362686,
      "to": 362687,
      "along": 0,
      "distance_m": 6.001708302961281
    },
    {
      "lat": 19.418447264747087,
      "lon": -99.17902412186542,
      "from": 362688,
      "to": 361352,
      "along": 0,
      "distance_m": 6.1781608772235606
    },
    {
      "lat": 19.41828749262708,
      "lon": -99.17860207985096,
      "from": 361352,
      "to": 362389,
      "along": 0.045549726075291,
      "distance_m": 0.6426478129502552
    }
  ],
  "speed_limits_kmh": [
    50,
    null,
    null,
    null,
    null
  ],
  "classes": [
    "primary",
    "residential",
    "residential",
    "residential",
    "residential"
  ],
  "geometry": [],
  "distance_m": 1835,
  "duration_s": 154.9,
  "confidence": 0.8,
  "matched": 25,
  "unmatched": 0,
  "provenance": {
    "name": "overture-transportation",
    "release": "2026-08-19.0",
    "license": "ODbL-1.0"
  },
  "took_us": 3881
}

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: points shows 5 of 25. Shortened for the page: speed_limits_kmh shows 5 of 25. Shortened for the page: classes shows 5 of 25.

Every fix matched (matched: 25, unmatched: 0), 1,835 m along the roads in 154.9 s at the roads' own speeds. Each entry in points is where that fix landed: the edge it lies on (from, to), how far along it, and distance_m from where it was observed. speed_limits_kmh and classes run in step with points: the first fix is on a primary road posted at 50 km/h; the next are residential, with no posted limit in the data.

The program

It reads fixes.csv — vehicle, time in unix seconds, lat,lon — and writes trips.csv, one row per trip. Run the TypeScript withnpx tsx gps-cleanup.ts fixes.csv; see clients.

Python
"""Clean fleet GPS: split each vehicle's fixes into trips, match them to the
roads, and report mileage and time over the posted limit per trip.

    python gps_cleanup.py fixes.csv      # columns: vehicle, time, lat, lon

time is unix seconds. Writes trips.csv.
"""

import csv
import math
import sys
from collections import defaultdict

from oslew import Client, retry_on_rate_limit

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

MAX_POINTS = 10_000   # the most one match request takes
TRIP_GAP_S = 600      # ten minutes without a fix ends a trip
SIGMA_M = 4.07        # your receivers' noise in metres; the service's default
TOLERANCE_KMH = 5     # speed noise from GPS jitter; less over the limit than this is not counted
MAX_STEP_S = 60       # over a longer gap an "average speed" says nothing about speeding


def metres(a, b):
    """Great-circle distance between (lat, lon) pairs."""
    p, q = math.radians(a[0]), math.radians(b[0])
    h = (math.sin((q - p) / 2) ** 2
         + math.cos(p) * math.cos(q) * math.sin(math.radians(b[1] - a[1]) / 2) ** 2)
    return 2 * 6_371_000 * math.asin(math.sqrt(h))


def trips(fixes):
    """Time-ordered fixes, cut wherever the vehicle went quiet."""
    fixes.sort()
    trip = [fixes[0]]
    for fix in fixes[1:]:
        if fix[0] - trip[-1][0] > TRIP_GAP_S:
            yield trip
            trip = []
        trip.append(fix)
    yield trip


def match(trip):
    """The whole trip matched, in requests of at most MAX_POINTS. Each request
    after the first starts on the last fix of the one before, so the step
    between them is routed once and counted once."""
    points, limits, road_m, start = [], [], 0.0, 0
    while True:
        chunk = trip[start : start + MAX_POINTS]
        answer = retry_on_rate_limit(client.match, {
            "points": [{"lat": lat, "lon": lon, "time": t} for t, lat, lon in chunk],
            "sigma_m": SIGMA_M,
            "geometry": False,
        }, attempts=5)
        skip = 1 if start else 0  # the shared fix is already in hand
        points += answer["points"][skip:]
        limits += answer["speed_limits_kmh"][skip:]
        road_m += answer["distance_m"]
        if start + MAX_POINTS >= len(trip):
            return points, limits, road_m
        start += MAX_POINTS - 1


def measure(vehicle, trip):
    row = {"vehicle": vehicle, "start": trip[0][0], "end": trip[-1][0], "fixes": len(trip)}
    if len(trip) == 1:
        # One fix is not a path. Snap it instead: snap looks up to ~9 km for
        # a road, where match looks only within search_m.
        s = client.snap(f"{trip[0][1]},{trip[0][2]}")
        return {**row, "matched": 0, "note": f"one fix, beside a {s['class'] or 'no'} road"}
    matched, limits, road_m = match(trip)
    gap_m = limited_s = over_s = 0.0
    good = [i for i, p in enumerate(matched) if p]  # unmatched fixes are skipped over
    for i, j in zip(good, good[1:]):
        (t0, *p0), (t1, *p1) = trip[i], trip[j]
        if j > i + 1 or metres(p0, p1) > 2000:
            # The matcher does not route across an unmatched fix or a 2 km
            # jump, so road_m leaves this out; a straight line stands in.
            gap_m += metres(p0, p1)
            continue
        dt = t1 - t0
        if limits[i] is None or not 0 < dt <= MAX_STEP_S:
            continue
        # Straight line between two positions on the road: never more than
        # the road distance, so the speed errs low.
        a, b = matched[i], matched[j]
        kmh = metres((a["lat"], a["lon"]), (b["lat"], b["lon"])) / dt * 3.6
        limited_s += dt
        if kmh > limits[i] + TOLERANCE_KMH:
            over_s += dt
    n = len(trip)
    m = sum(1 for p in matched if p)
    close = sum(1 for p in matched if p and p["distance_m"] <= 2 * SIGMA_M)
    return {**row, "matched": m, "unmatched": n - m,
            "confidence": round(close / m * (m / n), 3) if m else 0.0,
            "road_km": round(road_m / 1000, 2), "gap_km": round(gap_m / 1000, 2),
            "limit_known_min": round(limited_s / 60, 1), "over_limit_min": round(over_s / 60, 1)}


fixes = defaultdict(list)
with open(sys.argv[1], newline="") as f:
    for r in csv.DictReader(f):
        fixes[r["vehicle"]].append((int(r["time"]), float(r["lat"]), float(r["lon"])))

rows = [measure(v, trip) for v, points in fixes.items() for trip in trips(points)]
fields = ["vehicle", "start", "end", "fixes", "matched", "unmatched", "confidence",
          "road_km", "gap_km", "limit_known_min", "over_limit_min", "note"]
with open("trips.csv", "w", newline="") as f:
    w = csv.DictWriter(f, fieldnames=fields)
    w.writeheader()
    w.writerows(rows)
print(f"{len(rows)} trips from {len(fixes)} vehicles")
TypeScript
// Clean fleet GPS: split each vehicle's fixes into trips, match them to the
// roads, and report mileage and time over the posted limit per trip.
//
//   npx tsx gps-cleanup.ts fixes.csv      # columns: vehicle, time, lat, lon
//
// time is unix seconds. Writes trips.csv.

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

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

const MAX_POINTS = 10_000; // the most one match request takes
const TRIP_GAP_S = 600; // ten minutes without a fix ends a trip
const SIGMA_M = 4.07; // your receivers' noise in metres; the service's default
const TOLERANCE_KMH = 5; // speed noise from GPS jitter; less over the limit than this is not counted
const MAX_STEP_S = 60; // over a longer gap an "average speed" says nothing about speeding

type Fix = [time: number, lat: number, lon: number];

// Great-circle distance between [lat, lon] pairs.
function metres(a: number[], b: number[]): number {
  const rad = Math.PI / 180;
  const h = Math.sin(((b[0] - a[0]) * rad) / 2) ** 2 +
    Math.cos(a[0] * rad) * Math.cos(b[0] * rad) * Math.sin(((b[1] - a[1]) * rad) / 2) ** 2;
  return 2 * 6_371_000 * Math.asin(Math.sqrt(h));
}

// Time-ordered fixes, cut wherever the vehicle went quiet.
function trips(fixes: Fix[]): Fix[][] {
  fixes.sort((a, b) => a[0] - b[0]);
  const out: Fix[][] = [[fixes[0]]];
  for (const fix of fixes.slice(1)) {
    const trip = out[out.length - 1];
    if (fix[0] - trip[trip.length - 1][0] > TRIP_GAP_S) out.push([fix]);
    else trip.push(fix);
  }
  return out;
}

// The whole trip matched, in requests of at most MAX_POINTS. Each request
// after the first starts on the last fix of the one before, so the step
// between them is routed once and counted once.
async function match(trip: Fix[]) {
  const points: (Matched | null)[] = [];
  const limits: (number | null)[] = [];
  let roadM = 0;
  for (let start = 0; ; start += MAX_POINTS - 1) {
    const chunk = trip.slice(start, start + MAX_POINTS);
    const answer = await retryOnRateLimit(() => client.match({
      points: chunk.map(([time, lat, lon]) => ({ lat, lon, time })),
      sigma_m: SIGMA_M,
      geometry: false,
    }), { attempts: 5 });
    const skip = start ? 1 : 0; // the shared fix is already in hand
    points.push(...answer.points.slice(skip));
    limits.push(...answer.speed_limits_kmh.slice(skip));
    roadM += answer.distance_m;
    if (start + MAX_POINTS >= trip.length) return { points, limits, roadM };
  }
}

async function measure(vehicle: string, trip: Fix[]) {
  const row = { vehicle, start: trip[0][0], end: trip[trip.length - 1][0], fixes: trip.length };
  if (trip.length === 1) {
    // One fix is not a path. Snap it instead: snap looks up to ~9 km for
    // a road, where match looks only within search_m.
    const s = await client.snap(`${trip[0][1]},${trip[0][2]}`);
    return { ...row, matched: 0, note: `one fix, beside a ${s.class ?? "no"} road` };
  }
  const { points: matched, limits, roadM } = await match(trip);
  let gapM = 0;
  let limitedS = 0;
  let overS = 0;
  const good = matched.flatMap((p, i) => (p ? [i] : [])); // unmatched fixes are skipped over
  for (let k = 0; k + 1 < good.length; k++) {
    const [i, j] = [good[k], good[k + 1]];
    const [t0, ...p0] = trip[i];
    const [t1, ...p1] = trip[j];
    if (j > i + 1 || metres(p0, p1) > 2000) {
      // The matcher does not route across an unmatched fix or a 2 km
      // jump, so roadM leaves this out; a straight line stands in.
      gapM += metres(p0, p1);
      continue;
    }
    const dt = t1 - t0;
    const limit = limits[i];
    if (limit === null || !(dt > 0 && dt <= MAX_STEP_S)) continue;
    // Straight line between two positions on the road: never more than
    // the road distance, so the speed errs low.
    const [a, b] = [matched[i]!, matched[j]!];
    const kmh = (metres([a.lat, a.lon], [b.lat, b.lon]) / dt) * 3.6;
    limitedS += dt;
    if (kmh > limit + TOLERANCE_KMH) overS += dt;
  }
  const n = trip.length;
  const m = good.length;
  const close = matched.filter((p) => p && p.distance_m <= 2 * SIGMA_M).length;
  return {
    ...row, matched: m, unmatched: n - m,
    confidence: m ? +((close / m) * (m / n)).toFixed(3) : 0,
    road_km: +(roadM / 1000).toFixed(2), gap_km: +(gapM / 1000).toFixed(2),
    limit_known_min: +(limitedS / 60).toFixed(1), over_limit_min: +(overS / 60).toFixed(1),
  };
}

const fixes = new Map<string, Fix[]>();
const [header, ...lines] = (await readFile(process.argv[2], "utf8")).trim().split(/\r?\n/);
const col = Object.fromEntries(header.split(",").map((name, i) => [name.trim(), i]));
for (const line of lines) {
  const f = line.split(","); // numbers and ids only, so no quoting to undo
  const list = fixes.get(f[col.vehicle]) ?? [];
  list.push([Number(f[col.time]), Number(f[col.lat]), Number(f[col.lon])]);
  fixes.set(f[col.vehicle], list);
}

const rows: Record<string, unknown>[] = [];
for (const [vehicle, points] of fixes) {
  for (const trip of trips(points)) rows.push(await measure(vehicle, trip));
}
const fields = ["vehicle", "start", "end", "fixes", "matched", "unmatched", "confidence",
  "road_km", "gap_km", "limit_known_min", "over_limit_min", "note"];
const cell = (v: unknown) => (v === undefined ? "" : /[",]/.test(String(v)) ? `"${String(v).replaceAll('"', '""')}"` : String(v));
await writeFile("trips.csv", [fields.join(","), ...rows.map((r) => fields.map((f) => cell(r[f])).join(","))].join("\n") + "\n");
console.log(`${rows.length} trips from ${fixes.size} vehicles`);

The decisions in it

What the matcher does, and the two knobs

It is the Newson–Krumm hidden Markov model. Each fix has up to five candidate positions, on roads withinsearch_m of it; a candidate is as likely as it is close, measured in units ofsigma_m, the receiver's noise; and a step between two candidates is as likely as the route between them is close in length to the straight line the trace drew. The jointly most likely sequence wins, which is why one noisy fix beside a side street does not pull the route into it.

  • search_m, default 50, clamped to 5–200: how far from a fix a road may be. A fix with no road that close is null.
  • sigma_m, default 4.07, clamped to 1–50: the noise you expect. Set it to your receivers', not to a hope.

Breaks: 2 km, and fixes with no road

Consecutive fixes more than 2,000 m apart start a new segment, and so does a fix with no road withinsearch_m. The matcher does not route across a break, so distance_m leaves it out. The program measures each break as a straight line between the matched fixes either side and reports it separately, as gap_km — so a single absurd jump is skipped over rather than counted as kilometres driven, and a long stretch with no fixes is counted at its straight length rather than lost.

Mind the sampling rate: at 120 km/h a fix every minute is 2 km apart, and a motorway trip sampled that sparsely matches as a string of one-point segments. A fix every 30 seconds or less keeps a trace whole.

Speeds are yours to compute

time on a point is carried and not used by the match; nothing in the answer is a speed you drove. The program takes consecutive matched fixes, divides the straight line between their positions on the road by the seconds between their timestamps, and compares that with the posted limit of the edge the step starts on:

  • Steps longer than a minute are skipped: an average over a long gap says nothing about speeding.
  • Steps with no posted limit are skipped, and the minutes that do have one are reported beside the minutes over, so the one number always comes with what it is out of. Which roads carry a posted limit depends on the road data for the area.
  • 5 km/h of tolerance, for the jitter left after matching.
  • The straight line between two positions on the road is never longer than the road between them, so the speed errs low — the right side to err on for a number that may end up in front of a driver.

Confidence, for a whole trip

confidence is the share of matched fixes within two sigma_m of their road, times the share matched at all: 0.8 above means 20 of the 25 fixes landed within 8.14 m. It is per request, so for a trip split into several the program recomputes it the same way over every fix. A low value with most fixes matched usually means sigma_m is set tighter than your receivers are — not that the match is wrong.

10,000 points at a time

A request carries 1 to 10,000 points; more is refused with 400 between 1 and 10000 points. The program sends a long trip in pieces, each after the first starting on the last fix of the one before, and drops that repeated fix from the second answer — so the step between pieces is routed once and counted once. Near a join each piece sees context on one side only, so the result can differ by metres from one long request. 10,000 fixes of lat, lon and time are about half a megabyte of JSON, well inside the 2 MB body limit; extra fields per point would count against it.

One fix: snap it

A trip of a single fix — a tracker that woke, reported and slept — has no path to match./v1/snap finds the nearest road, searching out to about 9 km where match looks only withinsearch_m, and says its class and posted limit:

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

{
  "at": [
    19.4326,
    -99.1332
  ],
  "snapped": {
    "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
  },
  "class": "living_street",
  "speed_limit_kmh": 30,
  "provenance": {
    "name": "overture-transportation",
    "release": "2026-08-19.0",
    "license": "ODbL-1.0"
  },
  "took_us": 320
}

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

Beyond 9 km, snapped is null and the status is still 200. Seesnapping to roads.

What to watch out for

  • Match on the right network. profile is driving by default; a fleet of bicycles matches onto cycling, which has its own network.
  • geometry is off in the program, to keep answers small. Turned on, it is the matched route as (lat, lon) pairs with every segment in one list — a straight line joins one segment to the next, and a map should not draw it as road.
  • Pace the requests. Routing on the Routing plan is five requests a second; the program retries on 429, and a fleet's worth of short trips is the case where it will need to.
  • A route no road can make between two matched fixes also breaks a segment, and is not visible in the answer; gap_km counts only the breaks the program can see.
  • Coverage. Matching needs the road data loaded where the vehicle drove; outside it every fix is null.

See map matching for the endpoint on its own.

Endpoints

POST/v1/matchrouting

Match a GPS trace onto the roads (Newson–Krumm HMM): per point the edge and position it most likely lies on, the matched route, its length and duration, and a confidence.

GET/v1/snaprouting

The nearest point on a road to a point, with the road's class and posted limit.