Skip to content

Instantly share code, notes, and snippets.

@noerw
Last active May 17, 2016 07:42
Show Gist options
  • Save noerw/0a57fe51f0e9cf942ad0 to your computer and use it in GitHub Desktop.
Save noerw/0a57fe51f0e9cf942ad0 to your computer and use it in GitHub Desktop.
R script to visualize GeoTIFFs in a Leaflet Map. Generates an HTML file containing this map
# dependencies on fedora23:
# gdal-devel geos-devel proj-devel proj-nad proj-epsg
library(htmlwidgets)
library(raster)
library(leaflet)
# PATHS TO INPUT / OUTPUT FILES
projectPath = "/home/kreis/git/geotiff/"
#imgPath = paste(projectPath,"data/cea.tif", sep = "")
#imgPath = paste(projectPath,"data/o41078a1.tif", sep = "") # bigger than standard max size (15431804 bytes is greater than maximum 4194304 bytes)
imgPath = paste(projectPath,"data/SP27GTIF.TIF", sep = "")
outPath = paste(projectPath, "leaflethtmlgen.html", sep="")
# load raster image file
r <- raster(imgPath)
# reproject the image, if necessary
#crs(r) <- sp::CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
# color palette, which is interpolated ?
pal <- colorNumeric(c("#000000", "#666666", "#FFFFFF"), values(r),
na.color = "transparent")
# create the leaflet widget
m <- leaflet() %>%
addTiles() %>%
addRasterImage(r, colors=pal, opacity = 0.9, maxBytes = 123123123) %>%
addLegend(pal = pal, values = values(r), title = "Test")
# save the generated widget to html
# contains the leaflet widget AND the image.
saveWidget(m, file = outPath, selfcontained = FALSE, libdir = 'leafletwidget_libs')
@noerw
Copy link
Author

noerw commented Nov 16, 2015

Ideas:

  • try with rMaps instead of leaflet
  • try with other data formats (sp)
  • use native colors of file
  • wrap in function & make it callable from cli with parameters
  • accept files bigger than 4MB. works, but is slow as hell

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment