Skip to content

Instantly share code, notes, and snippets.

@charliejhadley
Created February 28, 2018 12:39
Show Gist options
  • Save charliejhadley/2286159778b12490f0c270f41870aff4 to your computer and use it in GitHub Desktop.
Save charliejhadley/2286159778b12490f0c270f41870aff4 to your computer and use it in GitHub Desktop.
Great circles with sf
library("tidyverse")
#> ── Attaching packages ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── tidyverse 1.2.1 ──
#> ✔ ggplot2 2.2.1.9000 ✔ purrr 0.2.4
#> ✔ tibble 1.4.2 ✔ dplyr 0.7.4
#> ✔ tidyr 0.8.0 ✔ stringr 1.2.0
#> ✔ readr 1.1.1 ✔ forcats 0.2.0
#> ── Conflicts ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── tidyverse_conflicts() ──
#> ✖ dplyr::filter() masks stats::filter()
#> ✖ dplyr::lag() masks stats::lag()
library("sf")
#> Linking to GEOS 3.6.1, GDAL 2.1.3, proj.4 4.9.3
library("leaflet")
## Original dataset
journey_data <- tribble(
~start.long, ~start.lat, ~end.long, ~end.lat, ~year, ~name,
-0.118092, 51.509865, -119.698189, 34.420830, 1999, "London to Santa Barbara",
31.496773, 30.026300, 24.753574, 59.436962, 2000, "New Cairo to Tallinn",
126.633333, 45.75, 46.738586, 24.774265, 2001, "Charlie"
)
start_locs <- journey_data %>%
select(contains("start")) %>%
rename(long = start.long,
lat = start.lat) %>%
mutate(journey.id = row_number())
end_locs <- journey_data %>%
select(contains("end")) %>%
rename(long = end.long,
lat = end.lat) %>%
mutate(journey.id = row_number())
## Generate a new sf object with LINESTRINGs between the start and end location
journey_data_linestrings <- start_locs %>%
bind_rows(end_locs) %>%
sf::st_as_sf(coords = c("long","lat")) %>%
group_by(journey.id) %>%
arrange(journey.id) %>%
summarise() %>%
sf::st_cast("LINESTRING")
## Add these LINESTRINGs to the tibble!
st_geometry(journey_data) <- st_geometry(journey_data_linestrings)
## We need to add a coordinate system to the sf object, let's go with the canonical standard EPSG:4326
journey_data <- st_set_crs(journey_data, st_crs(4326))
## Make a map
journey_data %>%
st_segmentize(units::set_units(100, km)) %>%
leaflet() %>%
addTiles() %>%
addPolylines()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment