Skip to content

Instantly share code, notes, and snippets.

@wkmor1
Last active December 24, 2015 09:08
Show Gist options
  • Save wkmor1/6774703 to your computer and use it in GitHub Desktop.
Save wkmor1/6774703 to your computer and use it in GitHub Desktop.
convert raster objects or raster readable files to .kml overlay files
rasterToKML <- function(x, out='Rgrid', png=FALSE, name=out, proj="+proj=longlat") {
require(raster)
require(maptools)
require(rgdal)
require(rgeos)
x <- raster(x)
SG <- as(x, 'SpatialGridDataFrame')
proj4string(SG) <- CRS(proj)
SG <- GE_SpatialGrid(SG)
if(png) png <- sprintf('%s.png', out) else png <- tempfile()
png(file=png, width=SG$width, height=SG$height, bg="transparent")
par(mar=rep(0, 4), xaxs="i", yaxs="i")
plot.new()
plot.window(xlim=SG$xlim, ylim=SG$ylim)
plot(x, legend=FALSE, add=TRUE)
dev.off()
invisible(capture.output(kmlOverlay(SG, sprintf('%s.kml', out), png, name)))
if(file.exists(sprintf('%s.kml', out))) cat('KML file created')
else cat (':( Sorry. Something went horribly wrong')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment