Skip to content

find_nearest_stations

find_nearest_stations

find_nearest_stations(lat: float, lon: float, info: DataFrame, *, k: int = 1, max_radius_m: float | None = None) -> DataFrame

Return the k stations closest to (lat, lon), with a distance column.

Parameters:

Name Type Description Default
lat float

Query point (degrees).

required
lon float

Query point (degrees).

required
info DataFrame

Stations with lat and lon columns (e.g. a canonical StationInfo frame).

required
k int

Number of nearest stations to return.

1
max_radius_m float

If given, drop stations farther than this (so fewer than k may return).

None

Returns:

Type Description
DataFrame

info rows sorted by ascending distance, with a distance_m column.

See Also

GeoKDTree : The spatial index underneath. stations_near : Radius instead of k-nearest.

Source code in src/gbfs_toolkit/spatial/geometry.py
def find_nearest_stations(
    lat: float,
    lon: float,
    info: pd.DataFrame,
    *,
    k: int = 1,
    max_radius_m: float | None = None,
) -> pd.DataFrame:
    """Return the ``k`` stations closest to ``(lat, lon)``, with a distance column.

    Parameters
    ----------
    lat, lon : float
        Query point (degrees).
    info : pandas.DataFrame
        Stations with ``lat`` and ``lon`` columns (e.g. a canonical StationInfo frame).
    k : int, default 1
        Number of nearest stations to return.
    max_radius_m : float, optional
        If given, drop stations farther than this (so fewer than ``k`` may return).

    Returns
    -------
    pandas.DataFrame
        ``info`` rows sorted by ascending distance, with a ``distance_m`` column.

    See Also
    --------
    [`GeoKDTree`][gbfs_toolkit.GeoKDTree] : The spatial index underneath.
    [`stations_near`][gbfs_toolkit.stations_near] : Radius instead of k-nearest.
    """
    out = info.copy()
    if out.empty:
        out["distance_m"] = pd.Series(dtype="float64")
        return out.reset_index(drop=True)
    tree = GeoKDTree(out["lat"], out["lon"])
    n = len(out)
    kk = n if max_radius_m is not None else min(k, n)
    dist, idx = tree.query(lat, lon, k=kk)
    dist, idx = np.asarray(dist).ravel(), np.asarray(idx).ravel()
    out = out.iloc[idx].copy()
    out["distance_m"] = dist
    if max_radius_m is not None:
        out = out[out["distance_m"] <= max_radius_m]
    return out.head(k).reset_index(drop=True)