Search code examples
rgeospatialcomputational-geometrybounding-box

R: Remove overlapping area of bounding boxes and create a polygon


I would like to create a polygon bounding box that does not include 2 selected areas:

I have 2 bounding boxes:

bb1 <- c(xmin = 11.23602, ymin =  47.80478, xmax = 11.88867, ymax =  48.24261)
bb2 <- c(xmin = 11.46067, ymin = 48.05556 , xmax = 11.69851 ,ymax  = 

I can convert those to a point matrix with his function:

library(sf)
get_sc_bbox<- function(bb){
  return(st_coordinates(st_as_sfc(st_bbox(bb))))
}

How could I remove areas of bb2 from bb1 and create a new bounding box (a polygon) that would exclude those areas where bb2 overlapp bb1 ?


Solution

  • This should do it:

    suppressMessages(library(sf))
    suppressMessages(library(ggsflabel))
    
    # use st_bbox() to make it an actual bounding box,
    ## then st_as_sfc to make a it a polygon
    bb1 <- c(xmin = 11.23602, ymin =  47.80478, xmax = 11.88867, ymax =  48.24261) %>% 
      st_bbox() %>%
      st_as_sfc()
    bb2 <- c(xmin = 11.46067, ymin = 48.05556 , xmax = 11.69851 ,ymax  = 48.21477) %>% 
      st_bbox() %>%
      st_as_sfc()
    bb3 <- c(xmin = 12.08761161, ymin = 47.82664071, xmax = 12.17363439, ymax = 47.88453729) %>% 
      st_bbox() %>%
      st_as_sfc()
    
    #polygon covering all three rectangles
    bb_all <- st_union(bb1, bb2) %>%
      st_union(bb3) %>%
      st_bbox() %>%
      st_as_sfc()
    
    # remove bb3 and bb2 from the full bounding box
    polygon_with_holes <- st_difference(bb_all, bb3) %>%
      st_difference(bb2)
    
    ggplot(polygon_with_holes) + 
      geom_sf(fill = 'green', alpha = .3)
    

    Created on 2021-03-30 by the reprex package (v0.3.0)