#' This function obtains the area of a POLYGON geometry in a postgreSQL database.
#' @export
#' @title Obtains the area of a POLYGON geometry
#' @name pgArea
#' @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 area should be permanently added to the table in the database
#' @return A data.frame with the area of each object in the original table
#' @author Bruno Silva
pgArea <- 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 area double precision;
UPDATE %s SET area=ST_AREA(%s);", vecTable, vecTable, geom) %>%
RPostgreSQL::dbSendQuery(con[[1]], .)
sprintf("SELECT area FROM %s", vecTable) %>%
tableArea <- RPostgreSQL::dbGetQuery(con[[1]], .)
} else {
sprintf("SELECT ST_AREA(%s) FROM %s", geom, vecTable) %>%
tableArea <- RPostgreSQL::dbGetQuery(con[[1]], .)
}
return(tableArea)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.