Guides
Calculate shipping cost by distance
Price local delivery at checkout from real road distance — a base fee plus a per-mile rate — with caching, rounding rules and integer-cent math.
Updated Dec 1, 2026 View Markdown
Local delivery fees based on real road distance are fairer than flat fees and simpler than ZIP-code tables.
The pricing rule
A common rule: base fee + per-mile rate, rounded up, with a minimum and maximum. For example $4.99 + $0.85/mi, max 15 mi.
Implementation
Use integer cents to avoid floating-point money errors:
const BASE_CENTS = 499;
const PER_MILE_CENTS = 85;
const MAX_MILES = 15;
export async function deliveryQuote(store: { lat: number; lng: number }, customer: { lat: number; lng: number }) {
const url = new URL("https://api.wayline.cloud/v1/distance");
url.searchParams.set("origin", `${store.lat},${store.lng}`);
url.searchParams.set("destination", `${customer.lat},${customer.lng}`);
url.searchParams.set("units", "imperial");
const res = await fetch(url, { headers: { Authorization: `Bearer ${process.env.WAYLINE_API_KEY}` } });
if (!res.ok) throw new Error(`Wayline ${res.status}`);
const { distance_meters } = await res.json();
const miles = distance_meters / 1609.344;
if (miles > MAX_MILES) return { deliverable: false as const };
const cents = BASE_CENTS + Math.ceil(miles * 10) * Math.round(PER_MILE_CENTS / 10); // bill per 0.1 mi
return { deliverable: true as const, miles: Math.round(miles * 10) / 10, cents };
}Multiple stores
Quote from the nearest store by drive time using a 1 × N matrix — see Delivery radius.
Performance at checkout
- Geocode the address once and cache coordinates on the customer record.
- Cache the quote for the cart session so re-renders don't re-bill.
- Set a short timeout (2–3 s) with a fallback fee so a network blip never blocks checkout.
Related: E-commerce shipping rates · Distance reference