Skip to content

Instantly share code, notes, and snippets.

@jcheng5
Last active September 29, 2017 14:49
Show Gist options
  • Save jcheng5/a1c48a18d0ea3623c0e6 to your computer and use it in GitHub Desktop.
Save jcheng5/a1c48a18d0ea3623c0e6 to your computer and use it in GitHub Desktop.
leaflet raster example
# Prerequisites:
# devtools::install_github("jcheng5/rasterfaster")
# devtools::install_github("rstudio/leaflet@raster")
library(shiny)
library(leaflet)
showRaster <- function(r, defaultTiles = TRUE, colorFunc = colorBin("RdBu", c(minValue(r), maxValue(r)), 8)) {
if (!inherits(r, "RasterLayer")) {
stop("showRaster only works with raster layers")
}
if (!identical(r@file@driver, "raster")) {
stop("showRaster only works with .grd files")
}
ui <- tagList(
tags$head(tags$style(type="text/css",
"html, body { width: 100%; height: 100%; padding: 0; margin: 0; }"
)),
leafletOutput("map", width = "100%", height = "100%")
)
server <- function(input, output, session) {
output$map <- renderLeaflet({
l <- leaflet() %>% setView(0, 0, zoom = 1)
opacity <- 1
if (defaultTiles) {
l <- l %>% addTiles(options = tileOptions(noWrap = TRUE))
opacity <- 0.5
}
l <- l %>% addRaster(r, options = tileOptions(opacity = opacity, noWrap = TRUE, detectRetina = FALSE),
colorFunc = colorFunc)
l
})
}
shinyApp(ui, server, options = list(launch.browser = getOption("viewer", TRUE)))
}
# MUST be 1) .grd file, 2) with `numeric` data, and 3) in unprojected WGS84.
# If your raster is in a different file format, use writeRaster() to create
# a .grd version. Performance is quite insensitive to resolution/size, so
# provide the highest resolution data you can.
r <- raster::raster("your_raster_file_here.grd")
# Show the map
showRaster(r, TRUE)
@mgahan
Copy link

mgahan commented Jun 1, 2015

Do you know the specific CRS for unprojected WGS84? I have been using CRS("+init=epsg:4326") and it is quite a bit off.

@eliotmcintire
Copy link

I can confirm that this is not plotting correctly with CRS("+init=epsg:4326"), but it is "on the correct globe", within 100 km or so. It does not work correctly at all (i.e., not on the map of the world) if I use CRS("+init=epsg:3857"). Using epsg:3857 is correct for the leaflet package and works for adding a raster using addRasterLayer, but not here with showRaster.

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