reactive rasters leaflet/shiny

1,658 views
Skip to first unread message

Hugh Sturrock

unread,
Jun 28, 2016, 5:06:46 PM6/28/16
to Shiny - Web Framework for R
Hi all,

I"m trying to put together a shiny app with raster layers plotted over a leaflet map. The rasters are time series so I ahve a time slider to select which layer from a raster stack to plot. The code below works fine, but I'd like to use the reactive and leafletProxy functions to prevent the app from re-running the whole script (thereby resetting the setview, zoom and layers). But I can't work out how to script it. 


covariates <- stack(list.files(paste0(system.file(package="dismo"), '/ex'),
                               pattern='grd', full.names=TRUE))


map = leaflet() %>% addTiles('http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png',
                                    attribution = paste(
                                      '&copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors',
                                      '&copy; <a href="http://cartodb.com/attributions">CartoDB</a>'
                                    ))


shinyServer(function(input, output){
  
output$myMap = renderLeaflet({
  map %>% addRasterImage(covariates[[input%layer]])
})
})



# This is what I was trying but I've got it wrong..


shinyServer(function(input, output){
  
output$myMap = renderLeaflet({
  map
})

rasterReactive<-reactive({covariates[[input$layer]]})

observe({
  leafletProxy("myMap", data =rasterReactive()) %>%
  clearImages() %>% addRasterImage()
})

})

Joe Cheng

unread,
Jun 28, 2016, 8:21:48 PM6/28/16
to Hugh Sturrock, Shiny - Web Framework for R
1) Remove data arg from leafletProxy
2) Pass raster to addRasterImage
3) Add a hard coded layerId to addRasterImage, otherwise you'll just keep adding more and more rasters to the map

Sorry for terseness, phone

--
You received this message because you are subscribed to the Google Groups "Shiny - Web Framework for R" group.
To unsubscribe from this group and stop receiving emails from it, send an email to shiny-discus...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/shiny-discuss/d1fc3291-e8d4-41a2-8258-ae881f49229b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Hugh Sturrock

unread,
Jun 29, 2016, 1:02:20 AM6/29/16
to Joe Cheng, Shiny - Web Framework for R
HI Joe,

Thanks! But I must be doing something wrong…Any ideas? code below

server.R

# download and load data
covariates <- stack(list.files(paste0(system.file(package="dismo"), '/ex'),
pattern='grd', full.names=TRUE))

map = leaflet() %>% addTiles('http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',
attribution = paste(
'&copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors'
))

shinyServer(function(input, output){

output$raster_map = renderLeaflet({
map})

reactiveRaster <- reactive({covariates[[input$integer]]})

observe({
leafletProxy("raster_map") %>%
clearImages() %>%
addRasterImage(reactiveRaster)
})

})



UI.R

shinyUI(fluidPage(
sliderInput("integer", "Time period",
min=1, max=12, value=1, ticks=F),

mainPanel(leafletOutput('raster_map', width=1500,height=800))
)
)


Joe Cheng

unread,
Jun 29, 2016, 1:36:55 AM6/29/16
to Hugh Sturrock, Shiny - Web Framework for R
There might be something else too, but addRasterImage(reactiveRaster) should be addRasterImage(reactiveRaster()).

Hugh Sturrock

unread,
Jun 29, 2016, 10:48:21 AM6/29/16
to Joe Cheng, Shiny - Web Framework for R
Works! Thanks!

prasenjit acharya

unread,
Mar 5, 2019, 9:16:33 AM3/5/19
to Shiny - Web Framework for R
Hi
I have been gone through the discussion in this post. It is an interesting post for the shiny users. However, I have been facing similar problem in shiny using raster image. Since I am new in shiny, I vehemently need your help to resolve this. Any suggestions are welcome. I am attaching the code below. 
rst <- raster('/home/prasenjit/Documents/prasenjit docs/ndvi_map.tif')
ui <- bootstrapPage(
  tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
  leafletOutput("map", width = "100%", height = "100%"),
  absolutePanel(top = 10, right = 10,
                sliderInput("range", "ndvi", min(values(rst)), max(values(rst)),
                            value = range(values(rst)), step = 0.1)
                #checkboxInput("legend", "Show legend", TRUE)
  )
)

server <- function(input, output, session) {
  filteredData <- reactive({
    overlay(rst[[input$range]], fun = function(x){
      if(is.na() == T){x <- NA} else if(x >=input$range[1] && x <=input$range[2]){x*1} else(x <- NA)
  })
  })
  pal <- colorNumeric("RdYlBu", values(rst), 
                      na.color = "transparent")
  output$map <- renderLeaflet({
  leaflet() %>% addTiles() %>%
    addRasterImage(rst, colors = pal, opacity = 1) %>%
    addLegend(position = "bottomright", pal = pal, values = values(rst),
              opacity = 1)
    observe({
      leafletProxy("map") %>%
        clearImages() %>%
        addRasterImage(filteredData(), colors = pal, opacity = 1)
    })
  })
}
shinyApp(ui, server)

Listening on http://127.0.0.1:3292
Warning: Error in inherits: cannot use this formula, probably because it is not vectorized
  61: <Anonymous>
Reply all
Reply to author
Forward
0 new messages