knitr::opts_chunk$set( collapse = TRUE, comment = "#>" )
Two-dimensional SpatRaster
objects (from the terra
package) or RasterLayer
objects (from the raster
package) can be turned into images and added to Leaflet maps using addRasterImage()
.
addRasterImage()
works by projecting the SpatRaster
or RasterLayer
object to EPSG:3857 and encoding each cell to an RGBA color, to produce a PNG image. That image is then embedded in the map widget.
It's important that the raster object is tagged with a proper coordinate reference system. Many raster files contain this information, but some do not. Here is how you'd tag a raster object "r
" which contains WGS84 data:
crs(r) <- "+proj=longlat +datum=WGS84"
Because addRasterImage()
embeds the image in the map widget, it will increase the size of the generated HTML proportionally. In order to avoid unacceptable download times and memory usage, addRasterImage()
will error when the PNG is beyond the size indicated by the maxBytes
argument (defaults to 4 megabytes).
If you have a large raster layer, you can provide a larger number of bytes and see how it goes, or use terra::resample()
, raster::resample()
, or raster::aggregate()
to decrease the number of cells.
addRasterImage()
projects using terra::project()
or raster::projectRaster()
, which can take a while on all but the smallest rasters. If you have a large raster layer or expect to call addRasterImage()
on the same raster layer many times, you can perform the EPSG:3857 projection yourself (either using leaflet::projectRasterForLeaflet()
or using another GIS library or program) and call addRasterImage()
with project = FALSE
.
Be sure that your pre-projected raster layer is tagged with an accurate extent and CRS, as these values are still needed to place the image in the proper position on the map.
In order to render the raster object as an image, each cell value must be converted to an RGB(A) color. You can specify the color scale using the colors
argument, which accepts a variety of color specifications:
colors
argument is provided, then "Spectral"
is the default.grDevices::col2rgb()
can be used, including "#RRGGBB"
and "#RRGGBBAA"
forms. Example: colors = c("#E0F3DB", "#A8DDB5", "#43A2CA")
.colors = colorBin("Greens", domain = NULL, bins = 5, na.color = "transparent")
.suppressPackageStartupMessages({ library(raster) r <- suppressWarnings(raster("nc/oisst-sst.nc")) }) library(leaflet) # ncdf4 emits partial match warnings
library(raster) library(leaflet) # you can download by accessing https://rstudio.github.io/leaflet/nc/oisst-sst.nc r <- raster("nc/oisst-sst.nc")
pal <- colorNumeric(c("#0C2C84", "#41B6C4", "#FFFFCC"), values(r), na.color = "transparent") leaflet() %>% addTiles() %>% addRasterImage(r, colors = pal, opacity = 0.8) %>% addLegend(pal = pal, values = values(r), title = "Surface temp")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.