R/gj_linestring_to_st_linestring.R

Defines functions gj_linestring_to_st_linestring

Documented in gj_linestring_to_st_linestring

#' Convert a GeoJSON linestring into an st_linestring
#'
#' @param gj_ls A GeoJSON linestring
#' @return The linestring as `sf::sfg`
#' @export
#' @family helpers
#' @examples
#' \dontrun{
#' gj_ls <- paste0(
#'   "-14.803659 128.403426 10.9 5.9;",
#'   "-14.803719 128.40326 1.7 1.9;",
#'   "-14.803756 128.40317 1.9 1.7;",
#'   "-14.80383 128.402983 1.7 1.6;",
#'   "-14.803913 128.402786 1.4 1.6;"
#' )
#' x <- gj_linestring_to_st_linestring(gj_ls)
#' class(x) == c("XYZM", "LINESTRING", "sfg")
#' }
gj_linestring_to_st_linestring <- function(gj_ls) {
  gj_ls %>%
    stringr::str_replace_all(";", " ") %>%
    stringr::str_split(" ") %>%
    purrr::map(as.numeric) %>%
    unlist() %>%
    # x[[1]]
    purrr::discard(is.na) %>%
    # last element generated by trailing ;
    matrix(nrow = 4) %>%
    # turn into matrix
    t() %>%
    # tip the matrix on its side
    tibble::as_tibble(.name_repair = "universal") %>%
    # name cols
    dplyr::transmute(
      lat = ...1,
      lon = ...2,
      alt = ...3,
      acc = ...4
    ) %>%
    dplyr::select(lon, lat, alt, acc) %>%
    # swap GJ YX to WKT XY
    as.matrix() %>%
    # st_linestring wants a matrix
    sf::st_linestring(dim = "XYZM")
}


# what's acc and what's alt
# test that coords are within sane bounds
# add to dl_odkc_2019

# usethis::use_test("gj_linestring_to_st_linestring")
parksandwildlife/wastdr documentation built on Nov. 17, 2022, 4:52 p.m.