#' This function obtains the centroid of a geometry in a postgreSQL database.
#' @export
#' @title Obtains the centroid of a geometry
#' @name pgCentroid
#' @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 newTable TRUE or FALSE. Indicates if a table with the buffer should be permanently added to the database
#' @return A SpatialPointsDataFrame object with the centroid of each object
#' @author Bruno Silva
pgCentroid <- function(con, vecTable, geom = NULL, newTable = NULL) {
if (is.null(geom)) geom <- checkGeom(con, vecTable)
if(length(geom) > 1) stop(paste0("Multiple geometries found. Please choose between: ",
geom))
if (is.null(newTable)) {
sprintf("SELECT ST_CENTROID(%s) INTO temptable FROM %s",
geom, vecTable) %>%
RPostgreSQL::dbSendQuery(con[[1]], .)
shape <- rgdal::readOGR(dsn = con[[2]], 'temptable')
RPostgreSQL::dbRemoveTable(con[[1]], 'temptable')
} else {
sprintf("SELECT ST_CENTROID(%s) INTO %s FROM %s",
geom, newTable, vecTable) %>%
RPostgreSQL::dbSendQuery(con[[1]], .)
shape <- rgdal::readOGR(dsn = con[[2]], newTable)
}
return(shape)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.