Problem with dynamic reactive objetc to raster leaflet integration

Hi Everyone!

I'd like to addRasterImage in leaflet by raster create dynamically by dbGetQuery in Shinny. The reactive objects ( pred_attack_BQ() ) are well specified, but reactive properties are lost during gridded and raster conversion. I don't have success and no plot are created:

Warning: Error in points2grid: dimension 1 : coordinate intervals are not constant
  105: stop
  104: points2grid
  103: SpatialPixels
  102: SpatialPixelsDataFrame
  101: asMethod
  100: as
   99: gridded<-
   97: ::
htmlwidgets
shinyRenderWidget [C:/Users/fores/Documents/reactive_raster_Shiny.r#87]
   96: func
   83: renderFunc
   82: output$map
    1: runApp


I try to do:

library(leaflet)
library(leaflet.providers)
library(ggplot2)
library(shinythemes)
library(sf)
library(dplyr)
library(rgdal)
library(rgeos)
library(DBI)
library(glue)

# get AOI
download.file(
  "https://github.com/Leprechault/trash/raw/main/stands_example.zip",
  zip_path <- tempfile(fileext = ".zip")
)
unzip(zip_path, exdir = tempdir())

# Open the files 
setwd(tempdir())
stands_extent <- readOGR(".", "stands_target") # Border
stands_ds <- read.csv("pred_target_stands.csv", sep=";") # Data set
stands_ds <- stands_ds %>%
  mutate(DATA_S2 = ymd(DATA_S2))
stands_ds$CLASS<-c(rep("A",129),rep("B",130)) 
stands_ds$CD<-abs(rnorm(length(stands_ds[,1]),mean=50))

# Crete like a SQL server condition
con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
DBI::dbWriteTable(con, "stands_ds", stands_ds)


# Create the shiny dash
ui <- fluidPage(
  theme = shinytheme("cosmo"),
  titlePanel(title="My Map Dashboard"),  
  sidebarLayout(
    sidebarPanel(
      selectInput(inputId = "selectedvariable0",
                  label = "Type", 
                  choices = c(unique(stands_ds$PEST)),selected = TRUE ), 
      selectInput(inputId = "selectedvariable1",
                  label = "Date", 
                  choices = c(unique(stands_ds$DATA_S)),selected = TRUE ), 
      selectInput(inputId = "selectedvariable2",
                  label = "Project", 
                  choices = c(unique(stands_ds$PROJETO)),selected = TRUE ),
      selectInput(inputId = "selectedvariable3",
                  label = "Stand", 
                  choices = c(unique(stands_ds$CD_TALHAO)),selected = TRUE),
      selectInput(inputId = "selectedvariable4",
                  label = "Unique ID", 
                  choices = c(unique(stands_ds$ID_UNIQUE)),selected = TRUE),
      selectInput(inputId = "selectedvariable5",
                  label = "Class", 
                  choices = c(unique(stands_ds$CLASS)),selected = TRUE)            
   ),
    mainPanel(
      textOutput("idSaida"),
      leafletOutput("map") 
    )
  )
)

server <- function(input, output, session){
      
 # Populate predictions with data set
    sqlInput_pred <- reactive({
       glue::glue_sql("SELECT * FROM stands_ds WHERE ID_UNIQUE = {x}", x = input$selectedvariable4, .con=con)
           })
    pred_attack_BQ <- function() dbGetQuery(con, as.character(sqlInput_pred()), stringsAsFactors = T)  


    output$map <- renderLeaflet({
      
           lng <- mean(as.numeric(pred_attack_BQ()$X))
           lat <- mean(as.numeric(pred_attack_BQ()$Y))
           
           #Convert stands_actual to raster
           stands_actual_ras<-data.frame(cbind(pred_attack_BQ()$X,pred_attack_BQ()$Y,pred_attack_BQ()$CD))
           colnames(stands_actual_ras)<-c("x","y","CD")
           # create spatial points data frame
           spg <- stands_actual_ras
           coordinates(spg) <- ~ x + y
           # coerce to SpatialPixelsDataFrame
           gridded(spg) <- TRUE
           # coerce to raster
           rasterDF <- raster(spg)
           crs(rasterDF) <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
           mypal <- colorNumeric(c("darkgreen", "yellow", "red"), values(rasterDF),
                                 na.color = "transparent")
           
           leaflet() %>%
             setView(lng = lng, lat = lat, zoom=15) %>%
             addProviderTiles(providers$Esri.WorldImagery) %>%
             addRasterImage(rasterDF, colors = mypal, opacity = 0.5) %>%
             addLegend(pal = mypal, values = values(rasterDF),
                       title = "CD (%)")
           addMarkers(lng=pred_attack_BQ()$X, lat=pred_attack_BQ()$Y, popup="Location")
      
    }) 
}
shinyApp(ui, server)

Please, any help with it? Thanks in advance!

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.