as_the_crow_flies <- function(city1, city2,
country1 = NULL, country2 = NULL,
units = "km", quiet = FALSE) {
gcl <- tidygeocoder::geo(
city = c(city1, city2), country = c(country1, country2),
method = "osm", quiet = TRUE, progress_bar = FALSE, verbose = FALSE
)
l1 <- gcl[1, ]
l2 <- gcl[2, ]
atcf <- wk::wk_handle(
wk::xy(c(l1$long, l2$long), c(l1$lat, l2$lat)),
wk::wk_linestring_filter(
wk::sfc_writer()
)
) |>
sf::st_as_sf(crs = "EPSG:4326") |>
sf::st_set_geometry("geometry")
d <- s2::s2_length(atcf) |> # nolint
units::set_units("m") |>
units::set_units(units, mode = "standard")
if (!quiet) {
cli::cli_alert_info("Distance as the crow flies = {round(d, 2)} {units}")
}
attr(atcf, "distance") <- d
return(atcf)
}
line_geom <- as_the_crow_flies("London", "Portsmouth")
#> ℹ Distance as the crow flies = 103.43 km
ggplot2::ggplot() +
ggspatial::annotation_map_tile(zoom = 9, alpha = 0.7) +
ggplot2::geom_sf(data = line_geom, colour = "#8410cc", lwd = 1.3) +
ggplot2::labs(
subtitle = glue::glue("Distance: {round(attr(line_geom, 'distance'), 2)} km")
)
Created on 2024-10-30 with reprex v2.1.1