R/erase.R

Defines functions lawn_difference

Documented in lawn_difference

#' Difference
#'
#' Finds the difference between two [data-Polygon]'s by clipping
#' the second polygon from the first.
#'
#' @export
#' @param poly1 A [data-Feature]<([data-Polygon])> feature
#' @param poly2 [data-Feature]<([data-Polygon])> to erase from poly1
#' @template lint
#' @family transformations
#' @return a [data-Feature]<([data-Polygon])> feature showing the area of poly1
#' excluding the area of poly2
#' @examples \dontrun{
#' # skipping on cran
#' poly1 <- '{
#'  "type": "Feature",
#'   "properties": {
#'     "fill": "#0f0"
#'   },
#'   "geometry": {
#'     "type": "Polygon",
#'     "coordinates": [[
#'       [-46.738586, -23.596711],
#'       [-46.738586, -23.458207],
#'       [-46.560058, -23.458207],
#'       [-46.560058, -23.596711],
#'       [-46.738586, -23.596711]
#'     ]]
#'   }
#' }'
#'
#' poly2 <- '{
#'   "type": "Feature",
#'   "properties": {
#'     "fill": "#00f"
#'   },
#'   "geometry": {
#'     "type": "Polygon",
#'     "coordinates": [[
#'       [-46.650009, -23.631314],
#'       [-46.650009, -23.5237],
#'       [-46.509246, -23.5237],
#'       [-46.509246, -23.631314],
#'       [-46.650009, -23.631314]
#'     ]]
#'   }
#' }'
#' lawn_difference(poly1, poly2)
#' }
#' @examples \dontrun{
#' lawn_featurecollection(list(poly1, poly2)) %>% view
#' lawn_difference(poly1, poly2) %>% view
#' fc <- lawn_featurecollection(list(
#'    lawn_polygon(jsonlite::fromJSON(poly1)$geometry$coordinates),
#'    lawn_polygon(jsonlite::fromJSON(poly2)$geometry$coordinates)
#' ))
#' view(fc)
#' }
lawn_difference <- function(poly1, poly2, lint = FALSE) {
  poly1 <- convert(poly1)
  poly2 <- convert(poly2)
  lawnlint(list(poly1, poly2), lint)
  if (lint) {
    is_type(poly1, "Feature", "Polygon")
    is_type(poly2, "Feature", "Polygon")
  }
  ct$eval(sprintf("var er = turf.difference(%s, %s);", poly1, poly2))
  structure(ct$get("er"), class = "polygon")
}
lawn_erase <- lawn_difference
ropensci/lawn documentation built on May 18, 2022, 9:58 a.m.