Skip to content

Instantly share code, notes, and snippets.

@mthh
Created September 5, 2016 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mthh/147fd029eb8e89c9c184c589302d86c1 to your computer and use it in GitHub Desktop.
Save mthh/147fd029eb8e89c9c184c589302d86c1 to your computer and use it in GitHub Desktop.
getHexGrid <- function(spdf, cellsize){
boundingBox <- bbox(spdf)
boundingBox[1,1] <- boundingBox[1,1] - cellsize
boundingBox[2,1] <- boundingBox[2,1] - cellsize
boundingBox[2,2] <- boundingBox[2,2] + cellsize
cols = ceiling(((boundingBox[1,2] - boundingBox[1,1]) + 3 * cellsize) / cellsize)
rows = ceiling((boundingBox[2,2] - boundingBox[2,1]) / cellsize)
x_left_origin = boundingBox[1,1]
y_bottom_origin = boundingBox[2,1]
xvertexlo = 0.288675134594813 * cellsize
xvertexhi = 0.577350269189626 * cellsize
x_spacing = xvertexlo + xvertexhi
output <- ""
for(col in seq(cols+1)){
x1 = x_left_origin + (col * x_spacing)
x2 = x1 + (xvertexhi - xvertexlo)
x3 = x_left_origin + ((col + 1) * x_spacing)
x4 = x3 + (xvertexhi - xvertexlo)
for(row in seq(rows+1)){
t = col %% 2
y1 = y_bottom_origin + (((row * 2) + t) * (cellsize / 2))
y2 = y_bottom_origin + (((row * 2) + t+1) * (cellsize / 2))
y3 = y_bottom_origin + (((row * 2) + t+2) * (cellsize / 2))
output <- paste0(output, "POLYGON((",
x1," ",y2 , ",", x2, " ", y1, ",", x3, " ", y1, ",",
x4, " ", y2, ",", x3, " ", y3, ",", x2, " ", y3, ",", x1, " ", y2, ")),")
}
}
spPoly <- rgeos::readWKT(paste0("GEOMETRYCOLLECTION(", substr(output, 1, nchar(output)-1), ")"))
return(SpatialPolygonsDataFrame(Sr = spPoly,
data = data.frame("id" = getSpPPolygonsIDSlots(spPoly))))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment