How to calculate driving distance in Python, JavaScript and Go

Copy-paste code to get real road distance and drive time in Python, Node.js and Go, with retries, caching and batching done right for production.

By Wayline Engineering · · Updated · 3 min read

Straight-line ("haversine") distance is easy to compute but wrong for anything a vehicle has to drive — it typically underestimates real trips, and not by a constant factor. This guide shows how to get road distance and drive time from an API in three languages, then how to make that code production-ready.

All examples use the Wayline Distance API. The same patterns apply to any routing API.

1. Get an API key

Create an account and copy a key from the dashboard. Keep it in an environment variable — never in source control:

bash
export WAYLINE_API_KEY="wl_live_..."

Use a wl_test_ key while developing; test keys are free and never billed.

2. One request with curl

Coordinates are lat,lng, the same order Google uses:

bash
curl "https://api.wayline.cloud/v1/distance?origin=37.788,-122.4075&destination=37.8044,-122.2712&units=imperial" \
  -H "Authorization: Bearer $WAYLINE_API_KEY"

The response includes distance_meters, duration_seconds and the map_version used, so you can reproduce a result later.

3. Python

python
import os
import httpx

API = "https://api.wayline.cloud"
client = httpx.Client(
    base_url=API,
    headers={"Authorization": f"Bearer {os.environ['WAYLINE_API_KEY']}"},
    timeout=10,
)

def driving_distance(origin: tuple[float, float], destination: tuple[float, float]) -> dict:
    r = client.get(
        "/v1/distance",
        params={"origin": f"{origin[0]},{origin[1]}", "destination": f"{destination[0]},{destination[1]}"},
    )
    r.raise_for_status()
    return r.json()

result = driving_distance((37.788,-122.4075), (37.8044,-122.2712))
print(result["distance_meters"] / 1609.344, "miles")

4. JavaScript / Node.js

js
const API = "https://api.wayline.cloud";

export async function drivingDistance(origin, destination) {
  const url = new URL("/v1/distance", API);
  url.searchParams.set("origin", `${origin.lat},${origin.lng}`);
  url.searchParams.set("destination", `${destination.lat},${destination.lng}`);
  const res = await fetch(url, {
    headers: { Authorization: `Bearer ${process.env.WAYLINE_API_KEY}` },
    signal: AbortSignal.timeout(10_000),
  });
  if (!res.ok) throw new Error(`Wayline ${res.status}: ${await res.text()}`);
  return res.json();
}

Call this from your backend. If you must call from a browser, restrict the key to your site's origin in the dashboard.

5. Go

go
func DrivingDistance(ctx context.Context, origin, dest string) (map[string]any, error) {
	u := "https://api.wayline.cloud/v1/distance?origin=" + url.QueryEscape(origin) +
		"&destination=" + url.QueryEscape(dest)
	req, _ := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
	req.Header.Set("Authorization", "Bearer "+os.Getenv("WAYLINE_API_KEY"))
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()
	if res.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("wayline: %s", res.Status)
	}
	var out map[string]any
	return out, json.NewDecoder(res.Body).Decode(&out)
}

6. Make it production-ready

Retry the right errors. Retry 429 and 5xx with exponential backoff and jitter, honoring Retry-After. Never retry 400-class validation errors — they will fail again. See errors and retries.

Batch instead of looping. Distances for many stops in order? One batch distance call replaces N single calls. Many origins to many destinations? Use the Distance Matrix API.

Cache stable answers. Distances between fixed points (warehouses, stores, customer addresses) change only when the map changes. Cache by rounded coordinates and store map_version with each value — the caching guide has the details.

Handle coverage. If a point is outside a supported region, the API returns OUT_OF_COVERAGE. Check the coverage page for supported regions.

Converting units

  • Meters to miles: divide by 1,609.344.
  • Meters to kilometers: divide by 1,000.
  • Seconds to minutes: divide by 60 and round for display.

Or pass units=imperial and format on the client.

FAQ

Can I calculate driving distance without an API? Only by running a routing engine and road data yourself. That works, but you take on data updates, servers and uptime.

Is there an official SDK? Yes — see the SDKs page for Python, JavaScript, Go and more.

How accurate is drive time? Wayline durations are free-flow estimates on OpenStreetMap roads, without live traffic. They suit pricing, planning and reimbursement; for rush-hour ETAs, add a buffer or use a traffic-aware provider.

GuidesDistanceCode

Start building in minutes

Create an account, grab a test key and make your first request in under five minutes.