Skip to contents

Computes the grid distance (minimum number of hops) between pairs of hexagonal cells. This is a discrete distance measured in cell steps, not a geodesic distance.

Usage

hex_distance(cell_a, cell_b, grid)

Arguments

cell_a, cell_b

Cell IDs. Must be the same length (pairs) or one of them length 1 (broadcast). For H3 grids, character vectors. For ISEA grids, numeric vectors.

grid

A HexGridInfo or HexData object specifying the grid.

Value

An integer vector of grid distances. NA where the distance cannot be computed (e.g., pentagon path issues in H3).

Details

H3 backend: Uses the vendored H3 gridDistance function. Returns the exact shortest path length in cell hops.

ISEA backend: Cells on the same quad are counted in the quad's own cell lattice, where the six neighbours are one step away and the distance is the axial hex distance max(|di|, |dj|, |di - dj|). The lattice is not always the substrate the cell IDs are packed on – at aperture 3's odd resolutions one substrate point in three is a cell – so the difference is divided by the lattice generator first. Cross-quad distances use breadth-first search over get_neighbors() and return NA beyond a hundred rings.

For geodesic (geographic) distances between cell centers, convert to lon/lat with cell_to_lonlat() and use sf::st_distance().

See also

get_neighbors() for finding cells within a given distance, cell_to_lonlat() for geographic coordinates

Examples

# \donttest{
# H3 grid distance
g <- hex_grid(resolution = 5, type = "h3")
a <- lonlat_to_cell(10, 50, g)
b <- lonlat_to_cell(10.1, 50.1, g)
hex_distance(a, b, g)
# }

# ISEA: neighbouring cells are one hop apart
g <- hex_grid(resolution = 3, aperture = 3)
a <- lonlat_to_cell(10, 50, g)
hex_distance(a, get_neighbors(a, g)[[1]], g)