oslew docs
Console
Menu

A store locator

A person types where they are — an address, a neighbourhood, a landmark — and wants the stores nearest to them. "Nearest" in a city is not a straight line: a river, a motorway or a one-way system can make the closest store on the map the slowest to reach. So the list should be ordered by travel time, with an honest fallback where no time can be computed.

The approach

  1. Locate the person with /v1/geocode. Whendecision.action is refuse (the words name several places equally well, or two too closely to call), ask which one rather than guessing.
  2. Shortlist the stores by straight-line distance, down to what one matrix may hold on your plan.
  3. Time them with one /v1/matrix request: the person first, then the stores. Row 0 of the answer is the time from the person to every store.
  4. Rank by that time, and place stores with no time after the rest, by distance, saying so.
  5. Optionally, list points of interest near the chosen store with/v1/nearby.

Three products: geocoding is address, the matrix is routing, nearby issearch. A plan with routing but not search still runs the locator; the program skips the last step. See products and plans.

The program

A command line version, so every decision is in view; in a web page, the same two functions sit behind your own server, as in the address form. The stores are your own table. Run the TypeScript with npx tsx store-locator.ts "…"; see clients.

Python
"""A store locator: where the person is, then which stores are nearest by road.

    python store_locator.py "Avenida Insurgentes Sur 1602, 03940"
"""

import math
import sys

from oslew import Client, PlanError

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

SIDE = 100  # the most points a matrix may have on a side on your plan
STORES = [  # your own table, geocoded once when each store opened
    {"name": "Polanco", "lat": 19.4406, "lon": -99.2047},
    {"name": "Centro", "lat": 19.4326, "lon": -99.1332},
    {"name": "Alameda", "lat": 19.4352, "lon": -99.1412},
    {"name": "Coyoacán", "lat": 19.3500, "lon": -99.1620},
]


def metres(a_lat, a_lon, b_lat, b_lon):
    """Great-circle distance: the fallback, and the pre-filter."""
    p, q = math.radians(a_lat), math.radians(b_lat)
    h = (math.sin((q - p) / 2) ** 2
         + math.cos(p) * math.cos(q) * math.sin(math.radians(b_lon - a_lon) / 2) ** 2)
    return 2 * 6_371_000 * math.asin(math.sqrt(h))


def locate(text):
    """One place, or the places the text could equally mean."""
    answer = client.geocode(text, limit=5)
    results = answer["results"]
    if not results:
        return results
    if answer["tied_at_top"] > 1:
        return results[: answer["tied_at_top"]]  # equally good: offer them all
    if answer["decision"]["action"] == "refuse":
        return results                           # too close to call: offer the close ones
    return results[:1]


def rank(lat, lon, show=3):
    """Stores by driving time from (lat, lon); by distance where no time exists."""
    near = sorted(STORES, key=lambda s: metres(lat, lon, s["lat"], s["lon"]))[: SIDE - 1]
    points = ";".join(f"{p['lat']},{p['lon']}" for p in [{"lat": lat, "lon": lon}, *near])
    row = client.matrix(points, profile="driving")["durations_s"][0]  # from the person
    ranked = [{**s, "seconds": row[j], "metres": metres(lat, lon, s["lat"], s["lon"])}
              for j, s in enumerate(near, start=1)]
    # Timed stores first, fastest first; then the rest by straight-line distance.
    ranked.sort(key=lambda s: (s["seconds"] is None,
                               s["metres"] if s["seconds"] is None else s["seconds"]))
    return ranked[:show]


found = locate(" ".join(sys.argv[1:]))
if not found:
    sys.exit("Nothing matched that. Try a street and number, or add a postcode or city after a comma.")
if len(found) > 1:
    print("That could be several places. Which one?")
    for i, r in enumerate(found, start=1):
        h = r["hierarchy"]
        print(f"  {i}. {r['name']}, {', '.join(x for x in (h.get('locality'), h.get('region')) if x)}")
    found = [found[int(input("> ")) - 1]]
here = found[0]

try:
    stores = rank(here["lat"], here["lon"])
except PlanError as e:
    sys.exit(e.message)  # routing is not on this plan, or SIDE is larger than the plan's
for s in stores:
    how = (f"{s['seconds'] / 60:.0f} min by road" if s["seconds"] is not None
           else f"{s['metres'] / 1000:.1f} km in a straight line; no road time")
    print(f"{s['name']}: {how}")

# Somewhere to eat near the nearest store. `nearby` is the search product;
# a plan without it skips this rather than failing the page.
best = stores[0]
try:
    places = client.nearby(f"{best['lat']},{best['lon']}", category="restaurant", limit=3)
    for p in places["results"]:
        print(f"  near {best['name']}: {p['name']}, {p['distance_m']:.0f} m")
except PlanError:
    pass
TypeScript
// A store locator: where the person is, then which stores are nearest by road.
//
//   npx tsx store-locator.ts "Avenida Insurgentes Sur 1602, 03940"

import { createInterface } from "node:readline/promises";
import { Client, PlanError } from "@oslew/client";
import type { Resolved } from "@oslew/client";

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

const SIDE = 100; // the most points a matrix may have on a side on your plan
const STORES = [ // your own table, geocoded once when each store opened
  { name: "Polanco", lat: 19.4406, lon: -99.2047 },
  { name: "Centro", lat: 19.4326, lon: -99.1332 },
  { name: "Alameda", lat: 19.4352, lon: -99.1412 },
  { name: "Coyoacán", lat: 19.35, lon: -99.162 },
];

// Great-circle distance: the fallback, and the pre-filter.
function metres(aLat: number, aLon: number, bLat: number, bLon: number): number {
  const rad = Math.PI / 180;
  const h = Math.sin(((bLat - aLat) * rad) / 2) ** 2 +
    Math.cos(aLat * rad) * Math.cos(bLat * rad) * Math.sin(((bLon - aLon) * rad) / 2) ** 2;
  return 2 * 6_371_000 * Math.asin(Math.sqrt(h));
}

// One place, or the places the text could equally mean.
async function locate(text: string): Promise<Resolved[]> {
  const answer = await client.geocode(text, { limit: 5 });
  if (answer.results.length === 0) return [];
  if (answer.tied_at_top > 1) return answer.results.slice(0, answer.tied_at_top); // equally good
  if (answer.decision.action === "refuse") return answer.results; // too close to call
  return answer.results.slice(0, 1);
}

// Stores by driving time from (lat, lon); by distance where no time exists.
async function rank(lat: number, lon: number, show = 3) {
  const near = [...STORES]
    .sort((a, b) => metres(lat, lon, a.lat, a.lon) - metres(lat, lon, b.lat, b.lon))
    .slice(0, SIDE - 1);
  const points = [{ lat, lon }, ...near].map((p) => `${p.lat},${p.lon}`).join(";");
  const row = (await client.matrix(points, { profile: "driving" })).durations_s[0]; // from the person
  const ranked = near.map((s, i) => ({ ...s, seconds: row[i + 1], metres: metres(lat, lon, s.lat, s.lon) }));
  // Timed stores first, fastest first; then the rest by straight-line distance.
  ranked.sort((a, b) =>
    a.seconds === null || b.seconds === null
      ? Number(a.seconds === null) - Number(b.seconds === null) || a.metres - b.metres
      : a.seconds - b.seconds);
  return ranked.slice(0, show);
}

let found = await locate(process.argv.slice(2).join(" "));
if (found.length === 0) {
  console.log("Nothing matched that. Try a street and number, or add a postcode or city after a comma.");
  process.exit(1);
}
if (found.length > 1) {
  console.log("That could be several places. Which one?");
  found.forEach((r, i) => {
    const where = [r.hierarchy.locality, r.hierarchy.region].filter(Boolean).join(", ");
    console.log(`  ${i + 1}. ${r.name}, ${where}`);
  });
  const rl = createInterface({ input: process.stdin, output: process.stdout });
  found = [found[Number(await rl.question("> ")) - 1]];
  rl.close();
}
const here = found[0];

let stores;
try {
  stores = await rank(here.lat, here.lon);
} catch (e) {
  // Routing is not on this plan, or SIDE is larger than the plan's.
  if (e instanceof PlanError) throw new Error(e.message);
  throw e;
}
for (const s of stores) {
  const how = s.seconds !== null
    ? `${(s.seconds / 60).toFixed(0)} min by road`
    : `${(s.metres / 1000).toFixed(1)} km in a straight line; no road time`;
  console.log(`${s.name}: ${how}`);
}

// Somewhere to eat near the nearest store. `nearby` is the search product;
// a plan without it skips this rather than failing the page.
const best = stores[0];
try {
  const places = await client.nearby(`${best.lat},${best.lon}`, { category: "restaurant", limit: 3 });
  for (const p of places.results) console.log(`  near ${best.name}: ${p.name}, ${p.distance_m.toFixed(0)} m`);
} catch (e) {
  if (!(e instanceof PlanError)) throw e;
}

The decisions in it

Ties: ask, or ask for more

tied_at_top is how many candidates share the best score, counted before limit cut the list, so asking for five does not hide a tie of sixteen. The program offers the tied candidates — as many as it fetched — with their locality and region. Here is a name that stays ambiguous even narrowed to one city:

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

{
  "query": "OXXO",
  "name": "OXXO",
  "context": null,
  "parse": {
    "name": "OXXO",
    "method": "passthrough"
  },
  "context_resolution": null,
  "near": [
    19.4326,
    -99.1332
  ],
  "results": [
    {
      "doc": 312143,
      "name": "OXXO",
      "lat": 19.41387107720213,
      "lon": -99.18570872993081,
      "bbox": [
        19.413737020076393,
        19.414005134329585,
        -99.18583782221324,
        -99.18557963767167
      ],
      "precision": "poi",
      "precision_m": 6.756173533775122,
      "hierarchy": {
        "locality": "Miguel Hidalgo",
        "region": "CMX",
        "country": "MX",
        "category": "convenience_store",
        "postcode": null,
        "street": null
      },
      "normalized": {
        "locality": "Miguel Hidalgo",
        "region": "CMX",
        "country": "MX",
        "formatted": "OXXO, Miguel Hidalgo, CMX, MX"
      },
      "components": {
        "name": "exact",
        "house_number": "missing",
        "street": "missing",
        "locality": "missing",
        "region": "missing",
        "postcode": "missing",
        "country": "missing"
      },
      "confidence": 0.99148935,
      "why": {
        "tokens": [
          "oxxo"
        ],
        "matched": 1,
        "extra": 0,
        "mode": "all",
        "tied": true,
        "prominence": 0,
        "rerank": 75
      },
      "provenance": {
        "name": "overture-places",
        "release": "2026-08-19.0",
        "license": "CDLA-Permissive-2.0"
      },
      "attributes": null
    },
    {
      "doc": 312176,
      "name": "Oxxo",
      "lat": 19.41758879104772,
      "lon": -99.186833538943,
      "bbox": [
        19.417454733014733,
        19.417722849082416,
        -99.18696263183097,
        -99.18670444607832
      ],
      "precision": "poi",
      "precision_m": 6.756173533775122,
      "hierarchy": {
        "locality": "Miguel Hidalgo",
        "region": "CMX",
        "country": "MX",
        "category": "convenience_store",
        "postcode": null,
        "street": null
      },
      "normalized": {
        "locality": "Miguel Hidalgo",
        "region": "CMX",
        "country": "MX",
        "formatted": "Oxxo, Miguel Hidalgo, CMX, MX"
      },
      "components": {
        "name": "exact",
        "house_number": "missing",
        "street": "missing",
        "locality": "missing",
        "region": "missing",
        "postcode": "missing",
        "country": "missing"
      },
      "confidence": 0.99148935,
      "why": {
        "tokens": [
          "oxxo"
        ],
        "matched": 1,
        "extra": 0,
        "mode": "all",
        "tied": true,
        "prominence": 0,
        "rerank": 75
      },
      "provenance": {
        "name": "overture-places",
        "release": "2026-08-19.0",
        "license": "CDLA-Permissive-2.0"
      },
      "attributes": null
    },
    {
      "doc": 312833,
      "name": "Oxxo",
      "lat": 19.405177436199025,
      "lon": -99.184670458663,
      "bbox": [
        19.40504338092024,
        19.405311491479537,
        -99.18479955038647,
        -99.18454136696286
      ],
      "precision": "poi",
      "precision_m": 6.756173533775122,
      "hierarchy": {
        "locality": "Miguel Hidalgo",
        "region": "CMX",
        "country": "MX",
        "category": "convenience_store",
        "postcode": null,
        "street": null
      },
      "normalized": {
        "locality": "Miguel Hidalgo",
        "region": "CMX",
        "country": "MX",
        "formatted": "Oxxo, Miguel Hidalgo, CMX, MX"
      },
      "components": {
        "name": "exact",
        "house_number": "missing",
        "street": "missing",
        "locality": "missing",
        "region": "missing",
        "postcode": "missing",
        "country": "missing"
      },
      "confidence": 0.99148935,
      "why": {
        "tokens": [
          "oxxo"
        ],
        "matched": 1,
        "extra": 0,
        "mode": "all",
        "tied": true,
        "prominence": 0,
        "rerank": 75
      },
      "provenance": {
        "name": "overture-places",
        "release": "2026-08-19.0",
        "license": "CDLA-Permissive-2.0"
      },
      "attributes": null
    }
  ],
  "mode": "all",
  "tied_at_top": 16,
  "tie_probe": 16,
  "interpolated": false,
  "decision": {
    "action": "refuse",
    "margin": 0,
    "disambiguation": {
      "tied": 16,
      "options": [
        {
          "rank": 1,
          "label": "OXXO, Miguel Hidalgo, CMX, MX",
          "country": "MX",
          "locality": "Miguel Hidalgo"
        },
        {
          "rank": 2,
          "label": "Oxxo, Miguel Hidalgo, CMX, MX",
          "country": "MX",
          "locality": "Miguel Hidalgo"
        },
        {
          "rank": 3,
          "label": "Oxxo, Miguel Hidalgo, CMX, MX",
          "country": "MX",
          "locality": "Miguel Hidalgo"
        },
        {
          "rank": 4,
          "label": "Oxxo, Miguel Hidalgo, CMX, MX",
          "country": "MX",
          "locality": "Miguel Hidalgo"
        },
        {
          "rank": 5,
          "label": "oxxo, MX",
          "country": "MX"
        },
        {
          "rank": 6,
          "label": "OXXO, San Pedro De Los Pinos, Ciudad de México, MX",
          "country": "MX",
          "locality": "San Pedro De Los Pinos"
        },
        {
          "rank": 7,
          "label": "Oxxo, Álvaro Obregón, CMX, MX",
          "country": "MX",
          "locality": "Álvaro Obregón"
        },
        {
          "rank": 8,
          "label": "OXXO, Ciudad de México, Ciudad de México, MX",
          "country": "MX",
          "locality": "Ciudad de México"
        }
      ]
    }
  },
  "epoch": 30,
  "release": "2026-08-19.0",
  "examined": 18,
  "postings": 25,
  "segments": 2,
  "store_requests": 0,
  "store_bytes": 0,
  "took_us": 361
}

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

Sixteen convenience stores share the top rank, and tie_probe is also 16: every candidate kept tied, so the true number is larger. When the choices cannot be told apart by what you can show — the same name in the same borough — a list does not help. Ask for a street, a postcode or a landmark instead.

Not tied is not always settled. decision.action is refuse when the best result is too close to the next to call, as for Museo Soumaya, which names two buildings; the program offers the close candidates then too. A result that is neither tied nor refused is used as it is. Its precision matters less here than for a delivery: a street or a neighbourhood's centre is a fine place to measure from when the answer is a list of stores minutes apart. See reading a result.

One row of a square matrix

A matrix is square: n points give n × n times, and the program reads one row. That is still the right tool — one request, one token, whatever its size — and it is why the store table is cut down first. SIDE is the most points your plan allows on a side: 100 on Routing, 200 on Platform, 500 on Scale. The person takes one place; the nearest SIDE − 1 stores by straight line take the rest. With stores reasonably dense, the one nearest by road is among them; if yours are sparse enough that it might not be, you have few enough to send them all.

curl
curl -G "https://api.oslew.com/v1/matrix" \
  -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'
Python
from oslew import Client

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

answer = client.matrix(
    "19.4406,-99.2047;19.4326,-99.1332;19.4352,-99.1412;19.3500,-99.1620",
)
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.matrix("19.4406,-99.2047;19.4326,-99.1332;19.4352,-99.1412;19.3500,-99.1620");
Response
HTTP/1.1 200 OK
content-type: application/json
ratelimit-limit: 100
ratelimit-remaining: 296
ratelimit-reset: 1

{
  "points": [
    [
      19.4406,
      -99.2047
    ],
    [
      19.4326,
      -99.1332
    ],
    [
      19.4352,
      -99.1412
    ],
    [
      19.35,
      -99.162
    ]
  ],
  "snapped": [
    {
      "node": 394836,
      "lat": 19.44024148258054,
      "lon": -99.20469439858863,
      "distance_m": 39.86969964600963
    },
    {
      "node": 355496,
      "lat": 19.432020221186303,
      "lon": -99.13343108985583,
      "distance_m": 68.87232944392214
    },
    {
      "node": 289914,
      "lat": 19.435305832231098,
      "lon": -99.14069479599135,
      "distance_m": 54.266522306414174
    },
    {
      "node": 368462,
      "lat": 19.35000467473249,
      "lon": -99.16174576953559,
      "distance_m": 26.677376568826062
    }
  ],
  "durations_s": [
    [
      0,
      693.5,
      561,
      814.5
    ],
    [
      691.5,
      0,
      212.1,
      651.1
    ],
    [
      546.3,
      170.5,
      0,
      745.7
    ],
    [
      791.1,
      656.5,
      732.8,
      0
    ]
  ],
  "engine": "base/hierarchy",
  "provenance": {
    "name": "overture-transportation",
    "release": "2026-08-19.0",
    "license": "ODbL-1.0"
  },
  "took_us": 2093
}

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

Point 0 is the Museo Soumaya; row 0 is the time from it to each point, in seconds: 693.5 to the Zócalo, 561 to the third point, 814.5 to the fourth. Column 0 is the other direction — from each point back — and differs, because one-way streets do: 691.5 from the Zócalo. A locator for people travelling to a store reads the row; one for deliveries from a store reads the column.

A larger matrix than the plan allows is refused, not trimmed:

Response
HTTP/1.1 403 Forbidden
content-type: application/json
ratelimit-limit: 5
ratelimit-remaining: 24
ratelimit-reset: 1

{
  "error": "this plan allows at most 3 points on a side; 4 were asked for. A larger matrix is what the next tier is for."
}

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

That is a 403 — PlanError in the clients — and retrying will not change it. The program stops and says so.

Null cells: say what you know

A duration is null when either end did not snap to a road within about 9 km, or when no route joins them. When the person's own point did not snap — snapped[0] is null — the whole row is null. The program ranks timed stores first and the rest after them by great-circle distance, printed as a distance, not dressed up as a time. A person told "4.2 km in a straight line" can judge it; one told "9 minutes" from a guessed speed cannot.

Times run between the road nodes nearest each point, so they differ by seconds from/v1/route, which snaps to the nearest edge — 693.5 s here against 695.2 s for the same trip by route. snapped[i].distance_m is how far a point was from its road: the walk from the car park is not in the time. See travel-time matrices.

Somewhere nearby

/v1/nearby lists places nearest a point, filtered by category: restaurant matches a whole category or a token of one, so mexican_restaurant counts. open_at=now keeps only places an attributes feed says are open, in the point's own time zone — and drops every place without hours, so use it only where hours are known. See nearby places and hours.

What to watch out for

  • Geocode each store once, when it opens, and keep its coordinates. Geocoding the table on every search spends the rate on answers that never change.
  • near filters; it does not bias. It keeps only results in about a city around the point. If you serve one city, pass its centre and a street name that exists elsewhere stops tying with those; if you serve a wider area, put the city or region after a comma as context instead. Seegeocoding.
  • A bare postcode is a question for /v1/postcode, which answers with the mean of the code's address points.
  • profile changes the network, not just the speed: each mode has its own network, speeds and access rules. Use walking for places people walk to. How far any of them reaches depends on the road data loaded for the area; see routes and profiles.
  • Keep the key on the server. A store locator is usually a web page; the matrix call belongs behind your own route.

Endpoints

GET/v1/geocodeaddress

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

GET/v1/matrixrouting

Travel times between every pair of up to 500 points.

GET/v1/nearbysearch

The nearest places to a point, nearest first, optionally of one category.