-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.R
298 lines (270 loc) · 11.2 KB
/
app.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
library(shiny)
library(bslib)
library(leaflet)
library(plotly)
library(dplyr)
library(ghcn) # Your custom package
library(DT)
library(httr)
library(shinyalert)
library(promises)
library(future)
library(shinyjs)
# Enable parallel processing
future::plan(multisession)
ui <- bslib::page_sidebar(
title = shiny::tags$span(style = "color: white; font-weight: bold;", "iSci GHCN-Daily Data Portal"),
theme = bslib::bs_theme(
bg = "#FFFFFF",
fg = "#000000",
primary = "#3398cb"
),
shinyjs::useShinyjs(),
# Add a container for the loading message
div(id = "loading-content",
style = "position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);
z-index: 9999; background-color: #f0f0f0; padding: 20px;
border-radius: 5px; text-align: center;
border: 2px solid #4a4a4a;",
h3("Checking NOAA CDO API Status. Please Wait...",
style = "color: #3398cb; margin-bottom: 15px;"),
tags$img(src = "isci_logo.png", height = "50px", style = "margin-bottom: 15px;"),
style = "display: none;"
),
sidebar = bslib::sidebar(
width = 300,
# Sidebar inputs
shiny::numericInput("radius", "Search Radius (km)", value = 10, min = 1, max = 500),
shiny::numericInput("limit", "Max Number of Stations", value = 10, min = 1, max = 50),
shiny::actionButton("search_stations", "Search Stations", class = "btn-custom"),
shiny::br(),
shiny::br(),
shiny::dateRangeInput("date_range", "Date Range",
start = Sys.Date() - 365, end = Sys.Date()),
shiny::selectizeInput("variables", "Select Variables",
choices = NULL,
multiple = TRUE,
options = list(maxItems = 5)),
shiny::actionButton("fetch_data", "Fetch Data", class = "btn-custom")
),
# Main content
bslib::layout_column_wrap(
width = 1,
heights_equal = "row",
# Map and Station Info Card
bslib::layout_columns(
col_widths = c(8, 4),
bslib::card(
full_screen = TRUE,
bslib::card_header("Station Map: Click to Establish Search Radius"),
leaflet::leafletOutput("station_map", height = 800)
),
bslib::card(
full_screen = TRUE,
bslib::card_header("Station Information"),
shiny::uiOutput("station_info")
)
),
# Plots and Data
bslib::navset_card_tab(
full_screen = TRUE,
bslib::nav_panel("Plots", plotly::plotlyOutput("data_plot", height = 800)),
bslib::nav_panel("Data", DT::dataTableOutput("data_table"))
)
),
# Custom CSS
tags$style(HTML("
.bslib-page-sidebar > .navbar { background-color: #3398cb !important; }
.bslib-sidebar-layout > .sidebar { background-color: #3398cb !important; }
.bslib-sidebar-layout > .sidebar { color: white !important; }
.bslib-sidebar-layout > .sidebar .form-control { color: black !important; background-color: white !important; }
.bslib-sidebar-layout > .sidebar .selectize-input { color: black !important; background-color: white !important; }
.btn-custom {
background-color: #ed5535 !important;
border-color: #ed5535 !important;
color: white !important;
}
.btn-custom:hover {
background-color: #d64a2e !important;
border-color: #d64a2e !important;
}
"))
)
server <- function(input, output, session) {
# Show loading message
shinyjs::show("loading-content")
# Perform API check
tryCatch({
base_url <- "https://www.ncei.noaa.gov/cdo-web/api/v2"
response <- httr::GET(
url = file.path(base_url, "stations"),
query = list(
datasetid = "GHCND",
limit = 5
),
httr::add_headers("token" = "jNgLeoBbPesCsXNbybBUwfTKPuXktBGS"),
httr::timeout(20)
)
if (httr::status_code(response) != 200) {
stop(paste("API request failed with status code:", httr::status_code(response)))
}
}, error = function(e) {
error_message <- if (inherits(e, "timeout")) {
"The NOAA CDO server was unresponsive and timed out after 20 seconds."
} else {
paste("The NOAA CDO server failed with the following error:", e$message)
}
shinyalert::shinyalert(
title = "NOAA CDO API Error",
text = error_message,
type = "error"
)
}, finally = {
# Hide loading message when done (success or failure)
shinyjs::hide("loading-content")
})
# Reactive values for storing the clicked point and selected station
clicked_point <- shiny::reactiveVal(NULL)
selected_station <- shiny::reactiveVal(NULL)
# Initialize the map
output$station_map <- leaflet::renderLeaflet({
leaflet::leaflet() %>%
leaflet::addTiles() %>%
leaflet::addAwesomeMarkers(lng = -98.5795, lat = 39.8283,
icon = leaflet::makeAwesomeIcon(icon = 'flag', markerColor = 'red', iconColor = 'white'),
label = "Click to select a location") %>%
leaflet::setView(lng = -98.5795, lat = 39.8283, zoom = 4) # Center on US
})
# Update clicked point when map is clicked
shiny::observeEvent(input$station_map_click, {
click <- input$station_map_click
clicked_point(c(lat = click$lat, lng = click$lng))
leaflet::leafletProxy("station_map") %>%
leaflet::clearMarkers() %>%
leaflet::addAwesomeMarkers(lng = click$lng, lat = click$lat,
icon = leaflet::makeAwesomeIcon(icon = 'flag', markerColor = 'red', iconColor = 'white'),
label = "Selected location")
})
# Reactive expression for getting stations
stations <- shiny::eventReactive(input$search_stations, {
point <- clicked_point()
shiny::req(point, input$radius, input$limit)
result <- ghcn::get_ghcn_daily_stations(
lat = point["lat"],
lon = point["lng"],
radius = input$radius,
limit = input$limit,
token = "jNgLeoBbPesCsXNbybBUwfTKPuXktBGS"
)
# Sort stations by distance
result %>%
dplyr::mutate(distance = sqrt((latitude - point["lat"])^2 + (longitude - point["lng"])^2)) %>%
dplyr::arrange(distance)
})
# Update map with station markers
shiny::observeEvent(stations(), {
req(stations())
leaflet::leafletProxy("station_map") %>%
leaflet::clearMarkers() %>%
leaflet::addAwesomeMarkers(data = stations(),
~longitude, ~latitude,
icon = leaflet::makeAwesomeIcon(icon = 'info-sign', markerColor = 'blue', iconColor = 'white'),
popup = ~paste(name, "<br>", id),
label = ~name,
layerId = ~id) %>%
leaflet::addAwesomeMarkers(lng = clicked_point()["lng"], lat = clicked_point()["lat"],
icon = leaflet::makeAwesomeIcon(icon = 'flag', markerColor = 'red', iconColor = 'white'),
label = "Selected location")
})
# Update selected station when a marker is clicked
shiny::observeEvent(input$station_map_marker_click, {
click <- input$station_map_marker_click
if (!is.null(click$id)) {
selected_station(stations() %>% dplyr::filter(id == click$id))
# Update the variables selectInput
available_vars <- unlist(strsplit(selected_station()$available_vars, ", "))
shiny::updateSelectizeInput(session, "variables", choices = available_vars, selected = character(0))
}
})
# Render station information card
output$station_info <- shiny::renderUI({
station <- selected_station()
if (is.null(station)) {
return(shiny::p("'Search Stations' after selecting a map location. Then click on a station marker to view its information."))
}
# Split available variables
available_vars <- strsplit(station$available_vars, ", ")[[1]]
shiny::tagList(
shiny::h5(station$name),
shiny::tags$div(
style = "line-height: 1.2; margin-bottom: 5px;",
shiny::p(shiny::strong("ID: "), station$id),
shiny::p(shiny::strong("Date Range: "), paste(station$mindate, "to", station$maxdate)),
shiny::p(shiny::strong("Distance: "), sprintf("%.2f km", station$distance * 111)), # Approximate conversion to km
shiny::p(shiny::strong("Latitude: "), station$latitude),
shiny::p(shiny::strong("Longitude: "), station$longitude),
shiny::p(shiny::strong("Elevation: "), station$elevation, " m")
),
shiny::h6("Available Variables:"),
shiny::tags$ul(
style = "padding-left: 20px; margin-top: 2px;",
lapply(strsplit(station$available_vars, ", ")[[1]], function(var) {
description <- ghcn::ghcn_daily_datatypes$description[ghcn::ghcn_daily_datatypes$datatype == var]
shiny::tags$li(
style = "margin-bottom: 2px;",
shiny::strong(var), ": ", description
)
})
)
)
})
# Reactive expression for getting data
station_data <- shiny::eventReactive(input$fetch_data, {
shiny::req(selected_station(), input$variables, input$date_range)
station <- selected_station()
# Check if selected date range is within the station's data range
station_start <- as.Date(station$mindate)
station_end <- as.Date(station$maxdate)
selected_start <- input$date_range[1]
selected_end <- input$date_range[2]
if (selected_start < station_start || selected_end > station_end) {
shiny::showModal(shiny::modalDialog(
title = "Date Range Error",
"The selected date range is outside the available data range for this station.
Please adjust your date selection or choose a different station.",
easyClose = TRUE,
footer = NULL
))
return(NULL)
}
ghcn::get_ghcn_daily_data(station_id = station$id,
start_date = selected_start,
end_date = selected_end,
token = "jNgLeoBbPesCsXNbybBUwfTKPuXktBGS",
datatype = input$variables)
})
# Render the data plot
output$data_plot <- plotly::renderPlotly({
shiny::req(station_data(), selected_station())
p <- ghcn::visualize_ghcn_daily_data(station_data(), selected_station()$name)
plotly::ggplotly(p)
})
# Render the data table
output$data_table <- DT::renderDataTable({
shiny::req(station_data())
DT::datatable(station_data(),
options = list(pageLength = 25,
order = list(list(0, 'desc')), # Sort by first column (date) in descending order
columnDefs = list(list(
targets = "_all",
render = DT::JS(
"function(data, type, row, meta) {",
"return type === 'display' && data != null && data !== ''",
" ? '<span style=\"font-size:0.7em;\">' + data + '</span>'",
" : data;",
"}"
)
))))
})
}
shiny::shinyApp(ui = ui, server = server)