Hi all,
I am using shiny app and managed to create an interesting map without a problem on Rstudio, but when I publish it I am getting "Disconnected from the server: Reload" in seconds, evethough the I set the waiting time to 60s. I am getting this error without any information on the log or rstudio. Can any one help how to fix this.
library(shiny)
library(leaflet)
library(plotly)
library(raster)
library(sp)
library(sf)
library(ncdf4)
#library(rgdal)
library(rsconnect)
# URLs for the NetCDF files on the server
url_data_nc <- "https://dap.ceda.ac.uk/thredds/dodsC/badc/hydro-jules/data/Global_drought_indices/MSWEP_hPET/Africa/Africa_spei01.nc"
url_data2_nc <- "https://dap.ceda.ac.uk/thredds/dodsC/badc/hydro-jules/data/Global_drought_indices/MSWEP_hPET/Africa/Africa_spei03.nc"
# Load raster stacks
r_list <- list(
stack((url_data_nc)),
stack((url_data2_nc))
)
ui <- fluidPage(
tags$head(tags$style(HTML('
#map {
cursor: pointer;
}
'))),
fluidRow(
column(7,
leafletOutput("map", width = "100%", height = "900px")
),
column(5,
style = "position: absolute; right: 10px; bottom: 150px;",
plotlyOutput("time_series_plot"),
absolutePanel(bottom = 500, left = 10,
selectInput("file_select", "Select file", choices = c("spei01.nc", "spei03.nc"), width = "150px")),
absolutePanel(bottom = 500, left = 200, selectInput("layer_select", "Select date", choices = NULL, width = "150px")),
verbatimTextOutput("click_info"),
downloadButton("time_series_download", "Download Time Series Data")
)
)
)
server <- function(input, output, session) {
# Update layer dropdown when file is selected
observeEvent(input$file_select, {
file_name <- input$file_select
r <- r_list[[which(file_name == c("spei01.nc", "spei03.nc"))]]
updateSelectInput(session, "layer_select", choices = names(r))
})
# Display values when the user clicks on the map
output$click_info <- renderPrint({
click <- input$map_click
if (is.null(click))
return(NULL)
file_name <- input$file_select
r <- r_list[[which(file_name == c("spei01.nc", "spei03.nc"))]]
clicked_point <- c(click$lng, click$lat)
lon <- clicked_point[1]
lat <- clicked_point[2]
# Determine the index of the clicked point
ncfile <- nc_open(url_data_nc) # Use the first file for metadata
# Specify the longitude and latitude coordinates
var_name <- "spei" # Replace with the actual variable name in your NetCDF file
lon_index <- which.min(abs(lon - ncfile$dim$lon$vals))
lat_index <- which.min(abs(lat - ncfile$dim$lat$vals))
# Specify the time indices for the desired period
start_time_index <- 1
end_time_index <- 492
values_list <- list()
# Loop through the time indices and extract values
for (time_index in start_time_index:end_time_index) {
values <- ncvar_get(ncfile, var_name,
start = c(lon = lon_index, lat = lat_index, time = time_index),
count = c(1, 1, 1))
values[is.na(values)] <- 1e30 # Replace NA with a specific value
values_list[[time_index]] <- values
}
values_ts <- unlist(values_list)
# print(values_ts)
value_str <- ifelse(is.na(values_ts), "NA", sprintf("%.2f", values_ts))
cat("SPEI: ", "Lat:", round(click$lat, 2), "Lon:", round(click$lng, 2))
})
output$map <- renderLeaflet({
file_name <- input$file_select
r <- r_list[[which(file_name == c("spei01.nc", "spei03.nc"))]]
r_subset <- r[[input$layer_select]]
# Clamp values to the range [-3.0, 3.0]
r_subset <- clamp(r_subset, upper = 3.0, lower = -3.0)
# Define color palette
color_pal <- colorNumeric(c("#67001f", "#a50026","#d73027","#f46d43", "#fdae61","#fee090","#ffffbf","#e0f3f8","#abd9e9",
"#74add1","#4575b4","#313695", "#313695"), domain = c(-3.01, 3.01),
na.color = "transparent")
leaflet() %>%
addTiles() %>%
addRasterImage(r_subset, colors = color_pal, opacity = .7) %>%
addLegend(pal = color_pal, values = values(r_subset),
title = "spei") #%>%
#addPolygons(data = shape, color = "black", fill = FALSE, weight = 1) %>%
#addPolygons(data = boundary, color = "black", fill = FALSE, weight = 1)#%>%
#addPolylines(data = rivers, color = "blue", weight = 1)
})
values_ts <- reactiveVal()
observeEvent(input$map_click, {
click <- input$map_click
if (!is.null(click)) {
file_name <- input$file_select
r <- r_list[[which(file_name == c("spei01.nc", "spei03.nc"))]]
# Extract the clicked latitude and longitude
clicked_point <- c(click$lng, click$lat)
lon <- clicked_point[1]
lat <- clicked_point[2]
# Determine the index of the clicked point
ncfile <- nc_open(url_data_nc) # Use the first file for metadata
# Specify the longitude and latitude coordinates
var_name <- "spei" # Replace with the actual variable name in your NetCDF file
lon_index <- which.min(abs(lon - ncfile$dim$lon$vals))
lat_index <- which.min(abs(lat - ncfile$dim$lat$vals))
# Specify the time indices for the desired period
start_time_index <- 1
end_time_index <- 504
values_list <- list()
# Loop through the time indices and extract values
for (time_index in start_time_index:end_time_index) {
values <- ncvar_get(ncfile, var_name,
start = c(lon = lon_index, lat = lat_index, time = time_index),
count = c(1, 1, 1))
values[is.na(values)] <- 1e30 # Replace NA with a specific value
values_list[[time_index]] <- values
}
values_ts <- as.numeric(unlist(values_list))
values_ts(values_ts)
# Show the time series plot in a modal dialog
showModal(modalDialog(
plotlyOutput("time_series_plot"),
title = "Time Series Plot"
))
}
})
output$time_series_plot <- renderPlotly({
ts <- values_ts ()# Retrieve the extracted time series
print(ts)
if (!is.null(ts)) {
data <- data.frame(Date = seq(as.Date("1981-01-01"), as.Date("2022-12-01"), by = "month"),
Value = ts)
lm_model <- lm(Value ~ as.numeric(as.Date(Date)), data)
plot_ly(data, x = ~Date, y = ~Value, type = 'scatter', mode = 'lines+markers') %>%
layout(title = "Time Series Plot", xaxis = list(title = "Date"), yaxis = list(title = "spei"))%>%
add_lines(x = ~Date, y = ~predict(lm_model, newdata = data),
name = "Trend Line", line = list(color = "red"))
}
})
output$time_series_download <- downloadHandler(
filename = function() {
paste("time_series_data", ".csv", sep = "")
},
content = function(file) {
ts <- values_ts()
if (!is.null(ts)) {
data <- data.frame(Date = seq(as.Date("1981-01-01"), as.Date("2022-12-01"), by = "month"),
Value = ts)
write.csv(data, file, row.names = FALSE)
}
}
)
}
shinyApp(ui, server)
after this I used rsconnect::deployApp(appDir = "C:/test/apps/data/", appPrimaryDoc = "pubApp.R", account = "solhailu", server = "shinyapps.io", appName = "Afroo")
to publish the app.