I'm writing a shiny app using leaflet. What I want to achieve is :
- render a simple leaflet map
- when click on a button, update rendering with "leafletProxy" to print a raster on top
- Being able to dynamically show raster value on mouse hover in a popup (like here, "labels" paragraph : https://rstudio.github.io/leaflet/popups.html)
I found the addImageQuery function from leafem package. Problem is 1) it doesn't display the value in a popup, and 2) it doesn't work with leafletProxy. See here : https://github.com/r-spatial/leafem/issues/7
Also found this : https://gis.stackexchange.com/questions/439185/getting-l-imageoverlay-raster-layer-pixel-value-at-coords-in-leaflet. Problem is I don't master javascript at all, and I think I would struggle a lot porting this solution in R.
Finally, I saw this post : Interactive plotting with R raster: values on mouseover. I had tried the solution proposed by SeGa to convert raster to sf object. But my raster is very large and it degrades severely the smoothness of the app.
Here is a minimal code example :
library(leaflet)
library(shiny)
library(dplyr)
library(sf)
ui <- fluidPage(
fluidRow(
leafletOutput(
"map",
width = 700,
height = 700
),
),
fluidRow(
actionButton(
inputId = "Action",
label = "Print raster"
)
)
)
server <- function(input, output) {
# Here I create a base map
output$map <- renderLeaflet(
{
leaflet() %>%
addProviderTiles("OpenStreetMap.France") %>%
setView(lat = 46.7, lng = 2, zoom = 6)
}
)
# udpate rendering with raster when button click
observeEvent(
input$Action,
{
pointSF <- st_sfc(st_point(c(2.5, 45.9)), crs = 4326)
buffer <- st_buffer(pointSF, dist = 200000)
grid <- st_make_grid(
buffer,
square = TRUE,
cellsize = c(0.1,0.1),
what = "centers"
) %>%
st_as_sf() %>%
cbind(., st_coordinates(.)) %>%
st_drop_geometry() %>%
mutate(Z = runif(nrow(.))) %>%
rename(x = X, y = Y, z = Z)
rast <- raster::rasterFromXYZ(grid, crs = 4326)
leafletProxy("map") %>%
addRasterImage(rast)
}
)
}
shinyApp(ui, server)
Any idea on how to achieve this properly ? Thanks guys.