R/pgLength.R

#' This function obtains the length of a LINE geometry in a postgreSQL database.
#' @export
#' @title Obtains the length of a LINE geometry
#' @name pgLength
#' @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 length should be permanently added to the table in the database
#' @return A data.frame with the length of each object in the original table
#' @author Bruno Silva
pgLength <- 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('MULTILINESTRING', 'LINESTRING') %>%   
    if(sum(.) == 0) stop(paste0('Only Lines or Multilines geometries allowed'))
  if (addColumn == TRUE)  { 
    sprintf("ALTER TABLE %s ADD COLUMN length double precision; UPDATE %s SET area=ST_LENGTH(%s);",
            vecTable, vecTable, geom) %>%
      RPostgreSQL::dbSendQuery(con[[1]], .) 
    tableLength <- 
      sprintf("SELECT length FROM %s", vecTable)  %>%
      RPostgreSQL::dbGetQuery(con[[1]], .)
  } else {
    #query <- sprintf("SELECT ST_LENGTH(%s) FROM %s", geom, vecTable)
    #tableLength <- RPostgreSQL::dbGetQuery(con[[1]], query)
    tableLength <- 
      sprintf("SELECT ST_LENGTH(%s) FROM %s", geom, vecTable) %>%
      RPostgreSQL::dbGetQuery(con[[1]], .)
  }   
  return(tableLength)
}
berdinazzi/easyPostGIS documentation built on May 12, 2019, 3:04 p.m.