# Nearest-driver selection

> Assign jobs to the closest available driver by actual drive time using the distance matrix API, with straight-line pre-filtering and batching tips.

Source: https://www.wayline.cloud/docs/guides/nearest-driver

The closest driver by straight line is often not the fastest to arrive. Rank candidates by **drive time** instead.

## 1. Snap the pickup

Riders drop pins in parks and buildings. Snap the pickup to the road first:

## 2. Pre-filter candidates

From your live driver locations, take the ~10–25 nearest by straight line. This keeps the matrix small (and cheap) without missing realistic candidates.

## 3. Rank by drive time

Send drivers as origins and the snapped pickup as the single destination:

```python
import os, requests

def rank_drivers(drivers, pickup):
    res = requests.post(
        "https://api.wayline.cloud/v1/matrix",
        json={"origins": [{"lat": d["lat"], "lng": d["lng"]} for d in drivers], "destinations": [pickup], "metrics": "duration"},
        headers={"Authorization": f"Bearer {os.environ['WAYLINE_API_KEY']}"},
        timeout=5,
    )
    res.raise_for_status()
    rows = res.json()["rows"]
    ranked = [
        (d, row["elements"][0]["duration_seconds"])
        for d, row in zip(drivers, rows)
        if row["elements"][0]["status"] == "OK"
    ]
    return sorted(ranked, key=lambda x: x[1])
```

## 4. Dispatch many jobs at once

For batch dispatch, build a drivers × jobs matrix and solve the assignment (e.g. the Hungarian algorithm). Stay within your plan's matrix element limit by tiling.

Related: [Rideshare & mobility](/use-cases/rideshare-mobility) · [Snap to Roads API](/products/snap-to-roads-api)
