addRasterImage function works by projecting the
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 “
which contains WGS84 data:
crs(r) <- "+proj=longlat +datum=WGS84"
Large Raster Warning
addRasterImage function 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
addRasterImage will error when the PNG is beyond the
size indicated by the
maxBytes argument (defaults to 4
If you have a large raster layer, you can provide a larger number of
bytes and see how it goes, or use
decrease the number of cells.
addRasterImage function projects using
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
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
colors argument, which accepts a variety of color
- The name of a Color Brewer 2
palette. If no
colorsargument is provided, then
"Spectral"is the default.
- A vector that represents the ordered list of colors to map to the
data. Any color specification that is accepted by
grDevices::col2rgbcan be used, including
colors = c("#E0F3DB", "#A8DDB5", "#43A2CA").
- A color scaling function, like those detailed in the Colors topic. For example:
colors = colorBin("Greens", domain = NULL, bins = 5, na.color = "transparent").
library(raster) 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")