Distance Matrix API: build a delivery-radius checker in 15 minutes
Decide in one request which of your stores can reach a customer within 20 minutes of driving, using a distance matrix, a pre-filter and caching.
By Wayline Engineering · · Updated · 2 min read
A 5-mile circle is the classic delivery zone — and it's wrong wherever a river, a highway or a one-way grid gets in the way. In this tutorial we'll build a checker that answers "which stores can reach this address in under 20 minutes?" with one Distance Matrix API request.
What we're building
An HTTP endpoint: POST /delivery-options { lat, lng } → the list of stores that can deliver, fastest first.
Step 1 — pre-filter cheaply
Don't send every store. Drop stores more than ~2× your drive-time radius at highway speed using straight-line distance. This keeps the matrix small and the bill predictable.
const R = 6371e3;
function haversine(a: { lat: number; lng: number }, b: { lat: number; lng: number }) {
const toRad = (d: number) => (d * Math.PI) / 180;
const dLat = toRad(b.lat - a.lat), dLng = toRad(b.lng - a.lng);
const h = Math.sin(dLat / 2) ** 2 + Math.cos(toRad(a.lat)) * Math.cos(toRad(b.lat)) * Math.sin(dLng / 2) ** 2;
return 2 * R * Math.asin(Math.sqrt(h));
}Step 2 — one matrix request
Stores are origins, the customer is the single destination, and we only ask for durations:
import { Wayline } from "@wayline/sdk";
const wayline = new Wayline({ apiKey: process.env.WAYLINE_API_KEY! });
export async function deliveryOptions(customer: { lat: number; lng: number }, stores: Store[], maxMin = 20) {
const candidates = stores.filter((s) => haversine(s, customer) < maxMin * 60 * 30); // ~30 m/s ceiling
if (!candidates.length) return [];
const m = await wayline.matrix({ origins: candidates, destinations: [customer], metrics: "duration" });
return candidates
.map((s, i) => ({ store: s, seconds: m.rows[i].elements[0].duration_seconds, ok: m.rows[i].elements[0].status === "OK" }))
.filter((x) => x.ok && x.seconds! <= maxMin * 60)
.sort((a, b) => a.seconds! - b.seconds!);
}Step 3 — cache the answer
Addresses repeat. Cache (store, rounded customer) → seconds and key it with the region's map_version so a map update refreshes it. See caching.
Cost
A request with N candidate stores costs N units. With a good pre-filter N is usually small. Estimate your monthly cost with the pricing calculator.
Caveats
Drive times are free-flow — no live traffic. Leave a margin or apply a time-of-day factor from your own delivery history.
Draft for review: add a before/after map image (radius vs drive-time zone) generated with the matrix generator tool.