Skip to content

Instantly share code, notes, and snippets.

@h-a-graham
Last active October 30, 2024 11:00
Show Gist options
  • Save h-a-graham/09d4b30cd31582cebee5391a6f6d37b1 to your computer and use it in GitHub Desktop.
Save h-a-graham/09d4b30cd31582cebee5391a6f6d37b1 to your computer and use it in GitHub Desktop.
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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment