R/bbox_to_SpatialPolygons.R

Defines functions bbox_to_SpatialPolygons

Documented in bbox_to_SpatialPolygons

#' Create a SpatialPolygons Bounding Box 
#'  
#' @param x Raster*, extent, bbox or matrix. See Details.
#' @param proj4string CRS object. Used to define the CRS if it is missing from x.
#' @return A SpatialPolygons object.
#' @author Jonathan A. Greenberg
#' @seealso \code{\link[sp]{bbox}}, \code{\link{extent}}
#' @details This function generates a SpatialPolygons object from either
#' a Raster* object, an extent object, a bbox object, or a 2x2 Matrix that follows the form
#' generated by the bbox() function (rows = x and y, cols = min and max).
#' Note that with extent and matrix objects, the CRS will need to be set
#' manually.
#' @examples
#' library("raster")
#' tahoe_highrez <- brick(system.file("external/tahoe_highrez.tif", package="spatial.tools"))
#' bbox_to_SpatialPolygons(tahoe_highrez)
#' tahoe_highrez_extent <- extent(tahoe_highrez)
#' bbox_to_SpatialPolygons(tahoe_highrez_extent,
#' 	CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
#' tahoe_highrez_bbox <- bbox(tahoe_highrez)
#' bbox_to_SpatialPolygons(tahoe_highrez_bbox,
#' 	CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
#' @import raster rgdal sp
#' @export

bbox_to_SpatialPolygons <- function(x,proj4string=CRS(as.character(NA)))
{	
	if(class(x)=="character")
	{
		x <- brick(x)	
	}
	
	
	if(class(x)=="RasterLayer" || class(x)=="RasterBrick" || class(x)=="RasterStack")
	{
		bbox <- bbox(x)
		proj4string <- CRS(projection(x))
	}
	
	if(class(x)=="Extent")
	{
		bbox <- matrix(c(
						x@xmin,
						x@ymin,
						x@xmax,
						x@ymax
				),nrow=2,ncol=2)
	}
	
	if(class(x)=="matrix")
	{
		bbox <- x
	}
	
	
	coords <- rbind(
			c(bbox[1,1],bbox[2,1]),
			c(bbox[1,2],bbox[2,1]),
			c(bbox[1,2],bbox[2,2]),
			c(bbox[1,1],bbox[2,2]),
			c(bbox[1,1],bbox[2,1])
	)
	
	bboxPolygon <- Polygon(coords)
	bboxPolygons <- Polygons(list(bboxPolygon),ID=1)
	bboxSpatialPolygons <- SpatialPolygons(list(bboxPolygons),proj4string=proj4string)
	return(bboxSpatialPolygons)
}

Try the spatial.tools package in your browser

Any scripts or data that you put into this service are public.

spatial.tools documentation built on May 2, 2019, 6:52 p.m.