R/pgPerimeter.R

#' This function obtains the perimeter of a POLYGON geometry in a postgreSQL database.
#' @export
#' @title Obtains the perimeter of a POLYGON geometry
#' @name pgPerimeter
#' @param con An object of class "pgConnect" generated by pgConnect()
#' @param vecTable Name of vectorial table in the database
#' @param geom A string with the name of a geometry type column. Only required if the table has more than 1 geometry columns
#' @param addColumn TRUE or FALSE. Indicates if a column with the perimeter should be permanently added to the table in the database
#' @return A data.frame with the perimeter of each object in the original table
#' @author Bruno Silva
pgPerimeter <- function(con, vecTable, geom = NULL, addColumn = FALSE){     
  if (is.null(geom)) geom <- checkGeom(con, vecTable)   
  if(length(geom) > 1) stop(paste0("Multiple geometries found. Please choose between: ", geom))   
  typeGeom(con, vecTable) == c('POLYGON', 'MULTIPOLYGON') %>% 
    if(sum(.) == 0) stop(paste0('Only Polygons or Multipolygons geometries allowed'))
  if (addColumn == TRUE)  { 
    sprintf("ALTER TABLE %s ADD COLUMN perimeter double precision;
               UPDATE %s SET perimeter=ST_PERIMETER(%s);", vecTable, vecTable, geom) %>%
      RPostgreSQL::dbSendQuery(con[[1]], .) 
    tablePerimeter <- 
      sprintf("SELECT perimeter FROM %s", vecTable) %>%
      RPostgreSQL::dbGetQuery(con[[1]], .)
  } else {
    tablePerimeter <- 
      sprintf("SELECT ST_PERIMETER(%s) FROM %s", geom, vecTable) %>%
      RPostgreSQL::dbGetQuery(con[[1]], query)
  }   
  return(tablePerimeter)
}
berdinazzi/easyPostGIS documentation built on May 12, 2019, 3:04 p.m.