-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.R
767 lines (676 loc) · 27.3 KB
/
server.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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
################################################################################
# This script is the server for the Destin CFA app
################################################################################
#remove(list = ls())
function(input, output, session) {
# Handle user authentication by only showing the main user interface when credentials are satisfied
shinyjs::hide(id="main_ui")
credentials <- shinyauthr::loginServer(
id = "login",
data = user_base,
user_col = user,
pwd_col = password,
sodium_hashed = TRUE,
log_out = reactive(logout_init())
)
logout_init <- shinyauthr::logoutServer(
id = "logout",
active = reactive(credentials()$user_auth)
)
# Dynamically display the UI according to login permissions
observeEvent(credentials()$user_auth, {
if (credentials()$user_auth) {
session$userData$user_id <- credentials()$info$user
shinyjs::show(id = "main_ui") # Show UI when logged in
} else {
shinyjs::hide(id = "main_ui") # Hide UI on logout
}
})
# Create modal dialog as a welcome/landing page
observe({
req(credentials()$info)
showModal(
ui = modalDialog(
title = "Welcome to the Charter Fishermen's Association Hotspot Mapper",
tags$div(
tags$p("This app allows you to filter data on a map, record new observations, and view your own recorded data over time."),
tags$h4("How to Use the App:"),
tags$ul(
tags$li("Use the filters in the sidebar to view all data in the Map tab."),
tags$li("Share your observations on the water in the Record New Observations tab."),
tags$li("View your own observations in the User Data tab.")
),
),
footer = tags$p(style="text-align:center;", tags$em("Data collected through this app is confidential and only accessible to approved members.")),
easyClose = TRUE,
fade = TRUE
)
)
})
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# If not utilizing usernames to filter data, create IDs based on session info
# if (is.null(session$userData$user_id)) {
# session$userData$user_id <- paste0("user_", substr(digest::digest(Sys.time()), 1, 8))
# }
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Create a reactiveValues object to store the Google Sheet data
data_store <- reactiveValues(data = NULL)
# Function to fetch and update the data from Google Sheet
update_sheet_data <- function() {
tryCatch({
sheet_data <- read_sheet(ss = sheet_id, sheet = "main")
data_store$data <- sheet_data
#show_alert("Data updated successfully", type="success", btn_colors = "#3b8dbc")
#showNotification("Data updated successfully", type="message")
}, error = function(e) {
showNotification("Error reading Google Sheet", type="error")
print(paste("Error reading sheet:", e))
})
}
# Fetch initial data on app startup
update_sheet_data()
# Confirm data entries
observeEvent(input$submit, {
#showNotification("submit button pressed")
#print("submit button pressed")
# Prevent duplicate entries due to double-clicking
#shinyjs::disable("submit")
ask_confirmation(
inputId = "confirm",
title = "Confirm Observations",
btn_colors = c("#dd4b39","#3b8dbc")
)
})
# perform error checks if data is confirmed
observeEvent(input$confirm,{
if (isTRUE(input$confirm)) {
timestamp <- Sys.time()
user_id <- session$userData$user_id
#print(input$geolocation)
# Check if the user wants to use the current location - turned off for now
if (input$check_loc == "Yes") {
if (input$geolocation == TRUE) {
lon <- as.numeric(input$long)
#print(input$long)
} else {
#showNotification("Unable to retrieve location. Please enter manually.", type = "error")
show_alert("Error writing data",
text = "Unable to retrieve location. Please enter manually.",
type="error", btn_colors = "#dd4b39")
return(NULL)
}
shinyjs::enable("submit")
#return(NULL)
} else {
lon <- as.numeric(input$text_long)
}
print(lon)
if (is.na(lon) || lon > -82.996 || lon < -90.500 || is.null(lon)) {
#print("Error: Longitude is outside the valid range.")
show_alert("Error writing data",
text = "Valid longitudes are between -90.5W and -83W.",
type="error", btn_colors = "#dd4b39")
#showNotification("Please enter a valid longitude between -89W and -83W.", type = "error")
shinyjs::enable("submit")
return(NULL)
}
if (input$check_loc == "Yes") {
if (input$geolocation == TRUE) {
lat <- as.numeric(input$lat)
#print(input$lat)
} else {
show_alert("Error writing data",
text = "Unable to retrieve location. Please enter manually.",
type="error", btn_colors = "#dd4b39")
#showNotification("Unable to retrieve location. Please enter manually.", type = "error")
return(NULL)
}
shinyjs::enable("submit")
#return(NULL)
} else {
lat <- as.numeric(input$text_lat)
}
print(lat)
if (is.na(lat) || lat < 28.90000 || lat > 30.692 || is.null(lat)) {
show_alert("Error writing data",
text = "Valid latitudes are between 28.9N and 30.6N.",
type="error", btn_colors = "#dd4b39")
#showNotification("Please enter a valid latitude between 28.9N and 30.5N.", type = "error")
shinyjs::enable("submit")
return(NULL)
}
notes <- if (input$text_notes == "") {
NA
} else {
input$text_notes
}
# Compile responses into a data frame
response_data <- data.frame(
current = input$select_current,
depred = input$select_depred,
species = input$select_species,
latitude = lat,
longitude = lon,
shared = input$check_share,
notes = notes,
timestamp = timestamp,
user_id = as.character(user_id)
)
#df(dplyr::bind_rows(df(), response_data))
#showNotification("Response data created")
values <- read_sheet(ss = sheet_id, sheet="main")
#showNotification(paste("Rows in sheet:", nrow(values)))
# Check to see if sheet has any existing data. If not, write to it and set up column names. Otherwise, append to it.
# Merge the new responses with the existing Google Sheet
tryCatch({
if (nrow(values) == 0) {
#showNotification("Writing new data to sheet")
sheet_write(data = response_data,
ss = sheet_id,
sheet = "main")
} else {
#showNotification("Appending data to sheet")
sheet_append(data = response_data,
ss = sheet_id,
sheet = "main")
#showNotification("Data recorded successfully", duration=5, type="message")
}
# Handle connectivity errors
update_sheet_data()
}, error = function(e) {
showNotification("Error writing to Google Sheet", type="error")
})
show_alert("Data updated successfully", type="success", btn_colors = "#3b8dbc")
shinyjs::enable("submit")
} else if (isFALSE(input$confirm)) {
return(NULL)
shinyjs::enable("submit")
}
}, ignoreNULL=TRUE) # End input confirm
# testvalues <- read_sheet(ss = sheet_id, sheet="main")
# print(testvalues)
# debugging
# observe({
# if (!is.null(data_store$data)) {
# print(sapply(data_store$data, class)) # Print the class of each column
# }
# })
#observe({
# output$sheet_data <- DT::renderDT({
# #read_sheet(ss = sheet_id, sheet = "main")
# req(data_store$data)
# data_store$data
# })
#})
################################################################################
# Filter dataset based on user inputs
filtered_prop <- reactive({
noaa_vl_des %>% filter(Days_Report <= input$days[1])#,
#Days_Report <= input$days[1])#,
#Effort_ID <= input$effort)
})
# Calculate fields for NOAA dataset
noaa_vl_prop <- reactive({
filtered_prop() %>%
filter(!is.na(LAT_BEGIN_SET) & !is.na(LON_BEGIN_SET)) %>%
group_by(UNIQUE_RETRIEVAL, COMMON_NAME, VESSEL_ID) %>%
mutate(
NUM_ALIVE = sum(NUM_FISH[CONDITION %in% c('ALIVE', 'ALIVE BAURO - STOM/BLADDER', 'ALIVE BAURO - EYES', 'ALIVE BAURO - BOTH')]),
NUM_DEAD = sum(NUM_FISH[CONDITION == 'DEAD']),
UNIQUE_RET_LAT = round(mean(LAT_BEGIN_SET), 6),
UNIQUE_RET_LON = round(mean(LON_BEGIN_SET), 6),
PROP_DEAD = NUM_DEAD / NUM_ALIVE,
NUM_SHARKS = sum(NUM_FISH[grepl("SHARK", COMMON_NAME)])
)
})
# Convert the data frame to a spatial object
noaa_vl_prop_sf <- reactive({st_as_sf(noaa_vl_prop(), coords = c("UNIQUE_RET_LON", "UNIQUE_RET_LAT"), crs = st_crs(gridshp))})
# Perform the spatial join
grid_join <- reactive({setDT(st_join(noaa_vl_prop_sf(), gridshp, join = st_intersects))})
#grid_join_dt <- setDT(grid_join)
# Filter and aggregate the data if the cells contain at least 3 vessels contributing
filtered_data <- reactive({
grid_join() %>%
group_by(GRID_ID) %>%
dplyr::reframe(
PROP_DEAD.mean = mean(PROP_DEAD, na.rm = TRUE), # Calculate the mean PROP_DEAD for each grid
NUM_SHARKS.mean = mean(NUM_SHARKS, na.rm=TRUE),
num_points = n(), # Count the number of points in each grid
unique_vessel_ids = n_distinct(VESSEL_ID) # Count unique VESSEL_IDs in each grid
) %>%
filter(num_points >= 3 & unique_vessel_ids >= 3) # Apply the filtering condition: at least 3 points and at least 3 unique VESSEL_IDs
})
filtered_data2 <- reactive({
filtered_data() %>%
filter(GRID_ID != "NA",
PROP_DEAD.mean != 'Inf') %>%
mutate(
depred_class = case_when(
PROP_DEAD.mean == 0 ~ 'None',
PROP_DEAD.mean <= 0.10 ~ 'Moderate',
PROP_DEAD.mean > 0.10 ~ 'High'
),
current_class = "None",
sharks_class = case_when(
NUM_SHARKS.mean == 0 ~ "None",
NUM_SHARKS.mean <= 2 ~ "Moderate",
NUM_SHARKS.mean > 2 ~ "High"
),
dolphins_class = "None"
)
})
# Merge the results back with the grid shapefile
gridvalues <- reactive({st_as_sf(merge(x = gridshp, y = filtered_data2(), by = "GRID_ID", all.x = FALSE))})
suppressWarnings(
grid_centroids <- reactive({
st_centroid(gridvalues()) %>% select(GRID_ID, depred_class, current_class, sharks_class, dolphins_class, num_points)
})
)
# grid_centroids_sd <- reactive({
# st_centroid(gridvalues()) %>% filter(depred_class != "None")
# })
######################################### user data
user_data <- reactive({data_store$data %>% #data_store$data %>% sheet_data %>%
filter(shared == "Yes" & !is.na(longitude) & !is.na(latitude)) %>% # only add shareable data
mutate(
current_bin = case_when(
current == "None" ~ 1,
current == "Moderate" ~ 2,
current == "High" ~3
),
depred_bin = case_when(
depred == "None" ~ 1,
depred == "Moderate" ~ 2,
depred == "High" ~3
)
)
})
user_data_sf <- reactive({st_as_sf(user_data(), coords = c("longitude", "latitude"), crs = st_crs(gridshp))})
grid_join_u <- reactive({setDT(st_join(user_data_sf(), gridshp, join = st_intersects))})
filtered_data_u <- reactive({
threshold_time <- Sys.time() - as.difftime(input$days, units = "days")
grid_join_u() %>%
filter(!is.na(GRID_ID),
timestamp >= threshold_time) %>%
group_by(GRID_ID) %>%
dplyr::reframe(
current.mean = mean(current_bin, na.rm = TRUE),
depred.mean = mean(depred_bin, na.rm=TRUE),
num_points = n(),
current_class = case_when(
current.mean == 1 ~ "None",
current.mean <= 2 ~ "Moderate",
current.mean > 2 ~ "High"
),
depred_class = case_when(
depred.mean == 1 ~ "None",
depred.mean <= 2 ~ "Moderate",
depred.mean > 2 ~ "High"
),
sharks_class = case_when(
species == "None" ~ "None",
species == "Dolphin" ~ "None",
species == "Shark" & depred.mean == 1 ~ "None",
species == "Shark" & depred.mean <= 2 ~ "Moderate",
species == "Shark" & depred.mean > 2 ~ "High"
),
dolphins_class = case_when(
species == "None" ~ "None",
species == "Shark" ~ "None",
species == "Dolphin" & depred.mean == 1 ~ "None",
species == "Dolphin" & depred.mean <= 2 ~ "Moderate",
species == "Dolphin" & depred.mean > 2 ~ "High"
),
all_notes = paste(notes[!is.na(notes)], collapse = ";<br> "),
num_points = n()
)
})
gridvalues_u <- reactive({st_as_sf(merge(x = gridshp, y = filtered_data_u(), by = "GRID_ID", all.x = FALSE))})
suppressWarnings(
grid_centroids_u <- reactive({
st_centroid(gridvalues_u()) %>% select(GRID_ID, depred_class, current_class, sharks_class, dolphins_class, num_points)
})
)
suppressWarnings(
all_centroids <- reactive({rbind(grid_centroids(), grid_centroids_u())})
)
#########################################
# Map with proxy
output$examplemap <- renderLeaflet({
req(credentials()$info)
showNotification("Update map in order to view data", duration=30, closeButton=TRUE)
leaflet() %>%
addProviderTiles("Esri.NatGeoWorldMap", options = providerTileOptions(minZoom = 6, maxZoom = 10)) %>%
setView(lng=-86.75, lat=29.75, zoom=9) %>%
addScaleBar(position = 'topleft',
options = scaleBarOptions(maxWidth = 100, metric = TRUE, imperial = TRUE, updateWhenIdle = FALSE))
})
colors <- c("#00a65a", "#f39c12", "#dd4b39")
pro_levels <- c("None", "Moderate", "High")
pro_pal <- colorFactor(colors, levels=pro_levels, domain=c("None", "Moderate", "High"))
observeEvent(input$update, {
popper <- paste0("<strong>Notes: </strong>observer data")
poppy <- paste0("<strong>Notes: </strong>", gridvalues_u()$all_notes)
proxy <- leafletProxy("examplemap")
proxy %>%
clearHeatmap() %>%
clearShapes() %>%
clearImages() %>%
clearControls() %>%
leafem::addMouseCoordinates() %>%
# addMarkers(lng=-86.3, #input$user_long
# lat=30.25, #input$user_lat
# icon=boat_icon) %>%
# addControl(html=html_legend, position="topright") %>%
addSimpleGraticule(interval = 1,
group = "Graticule") %>%
addLayersControl(position="topleft", overlayGroups = c("Graticule"),
options=layersControlOptions(collapsed=FALSE))
if (input$geolocation == TRUE) {
proxy %>%
addMarkers(lng=input$long,
lat=input$lat,
icon=boat_icon) %>%
addControl(html=html_legend, position="topright")
}
if (input$radio_depred == "Total" & input$radio_layer == "Intensity (grid)"){
proxy %>%
addPolygons(data = gridvalues(),
fillColor = ~pro_pal(depred_class),
weight = 0.5,
color = "black",
fillOpacity = 1,
highlightOptions = highlightOptions(color = "white", weight = 2, bringToFront = TRUE),
popup = ~popper,
group = "Depredation Intensity") %>%
addPolygons(data = gridvalues_u(),
fillColor = ~pro_pal(depred_class),
weight = 0.5,
color = "black",
fillOpacity = 1,
highlightOptions = highlightOptions(color = "white", weight = 2, bringToFront = TRUE),
popup = ~poppy,
group = "Depredation Intensity") %>%
leaflet::addLegend(position = 'topright',
pal = pro_pal,
values = c("None", "Moderate", "High"),
opacity = 1,
title = HTML("Depredation<br>Intensity"),
group = "Depredation Intensity",
layerId = "Depredation Intensity")
}
if (input$radio_depred == "Total" & input$radio_layer == "Density (heat)"){
proxy %>%
addHeatmap(data = all_centroids() %>% filter(depred_class != "None"),
#gradient = "Spectral",
intensity = ~num_points,
blur = 35,
#max = 0.05,
radius = 30,
group = "Catch Density")
}
if (input$radio_depred == "Sharks" & input$radio_layer == "Intensity (grid)"){
proxy %>%
addPolygons(data = gridvalues(),
fillColor = ~pro_pal(sharks_class),
weight = 0.5,
color = "black",
fillOpacity = 1,
highlightOptions = highlightOptions(color = "white", weight = 2, bringToFront = TRUE),
popup = ~popper,
group = "Shark Intensity") %>%
addPolygons(data = gridvalues_u(),
fillColor = ~pro_pal(sharks_class),
weight = 0.5,
color = "black",
fillOpacity = 1,
highlightOptions = highlightOptions(color = "white", weight = 2, bringToFront = TRUE),
popup = ~poppy,
group = "Shark Intensity") %>%
leaflet::addLegend(position = 'topright',
pal = pro_pal,
values = c("None", "Moderate", "High"),
opacity = 1,
title = HTML("Shark Intensity"),
group = "Shark Intensity",
layerId = "Shark Intensity")
}
if (input$radio_depred == "Sharks" & input$radio_layer == "Density (heat)"){
proxy %>%
addHeatmap(data = all_centroids() %>% filter(sharks_class != "None"),
#gradient = "Spectral",
intensity = ~num_points,
blur = 35,
#max = 0.05,
radius = 30,
group = "Shark Density")
}
if (input$radio_depred == "Dolphins" & input$radio_layer == "Intensity (grid)"){
proxy %>%
addPolygons(data = gridvalues(),
fillColor = ~pro_pal(dolphins_class),
weight = 0.5,
color = "black",
fillOpacity = 1,
highlightOptions = highlightOptions(color = "white", weight = 2, bringToFront = TRUE),
popup = ~popper,
group = "Dolphin Intensity") %>%
addPolygons(data = gridvalues_u(),
fillColor = ~pro_pal(dolphins_class),
weight = 0.5,
color = "black",
fillOpacity = 1,
highlightOptions = highlightOptions(color = "white", weight = 2, bringToFront = TRUE),
popup = ~poppy,
group = "Dolphin Intensity") %>%
leaflet::addLegend(position = 'topright',
pal = pro_pal,
values = c("None", "Moderate", "High"),
opacity = 1,
title = HTML("Dolphin Intensity"),
group = "Dolphin Intensity",
layerId = "Dolphin Intensity")
}
if (input$radio_depred == "Dolphins" & input$radio_layer == "Density (heat)"){
proxy %>%
addHeatmap(data = all_centroids() %>% filter(dolphins_class != "None"),
#gradient = "Spectral",
intensity = ~num_points,
blur = 35,
#max = 0.05,
radius = 30,
group = "Dolphin Density")
}
if (input$radio_current == "Yes"){
proxy %>%
clearHeatmap() %>%
clearControls() %>%
#clearShapes() %>%
addControl(html=html_legend, position="topright") %>%
addPolygons(
data=gridvalues(),
fillColor = ~pro_pal(current_class),
weight = 0.5,
color = "black",
fillOpacity = 1,
highlightOptions = highlightOptions(color = "white", weight = 2, bringToFront = TRUE),
popup = ~popper,
group = "Current Intensity") %>%
addPolygons(data = gridvalues_u(),
fillColor = ~pro_pal(current_class),
weight = 0.5,
color = "black",
fillOpacity = 1,
highlightOptions = highlightOptions(color = "white", weight = 2, bringToFront = TRUE),
popup = ~poppy,
group = "Current Intensity") %>%
leaflet::addLegend(position = 'topright',
pal = pro_pal,
values = c("None", "Moderate", "High"),
opacity = 1,
title = HTML("Current Intensity"),
group = "Current Intensity",
layerId = "Current Intensity")
}
})
#############################
# Print number of observations in the map
output$text_obs <- renderInfoBox({
infoBox(
"Total Observations",
paste0(format(sum(nrow(filtered_data()), nrow(filtered_data_u())), big.mark=",")),
icon=icon("binoculars"),
color="light-blue"
)
})
############################
# User data tab outputs
output$user_data <- DT::renderDT({
req(credentials()$info)
req(data_store$data)
data_store$data %>%
filter(
user_id %in% session$userData$user_id
) %>%
rename("Current Intensity" = "current",
"Depredation Intensity" = "depred",
"Species Encountered" = "species",
"Longitude" = "longitude",
"Latitude" = "latitude",
"Shared" = "shared",
"Notes" = "notes",
"Time Recorded (UTC)" = "timestamp",
"User ID" = "user_id")
})
userid_data <- reactive({
req(credentials()$info)
req(data_store$data)
data_store$data %>%
filter(!is.na(latitude) & !is.na(longitude) & user_id %in% session$userData$user_id)
})
calculateOpacity <- function(day_value) {
# Ensure there are timestamps to work with
if (length(day_value) == 0) return(rep(1, length(day_value))) # Default to opacity of 1 if no data
if (length(day_value) == 1) return(rep(1, length(day_value))) # Default to opacity of 1 if one data point
# Normalize the timestamps to get a range between 0 and 1
current_time <- Sys.time()
days_since <- as.numeric(difftime(current_time, day_value, units = "days"))
# Normalize the opacity (0 is more recent, 1 is the furthest back)
max_days <- max(days_since, na.rm = TRUE)
min_days <- min(days_since, na.rm = TRUE)
# Avoid division by zero
if (max_days == min_days) {
return(rep(1, length(day_value))) # Default opacity if all timestamps are the same
}
normalized_day <- (days_since - min_days) / (max_days - min_days)
opacity <- 1 - normalized_day # More recent data will be more opaque
return(opacity)
}
# Calculate colors for species - aligns with the input colors
colors_sp <- colorFactor(c("#00a65a","#3c8dbc", "#00c0ef"), levels = c("None", "Shark", "Dolphin"))
# Calculate opacity for days since recording
opacity <- reactive({
req(userid_data())
timestamps <- userid_data()$timestamp
calculateOpacity(timestamps)
})
# create user map
output$user_map <- renderLeaflet({
req(credentials()$info)
poppy <- paste0("<strong>Notes: </strong>", userid_data()$notes,
"<br><strong>Date Recorded: </strong>", as.Date(userid_data()$timestamp))
umap <- leaflet() %>%
addProviderTiles("Esri.NatGeoWorldMap", options = providerTileOptions(minZoom = 6, maxZoom = 12)) %>%
setView(lng=-86.75, lat=29.75, zoom=9) %>%
addScaleBar(position = 'topleft',
options = scaleBarOptions(maxWidth = 100, metric = TRUE, imperial = TRUE, updateWhenIdle = FALSE)) %>%
leafem::addMouseCoordinates() %>%
addSimpleGraticule(interval = 1,
group = "Graticule") %>%
#addControl(html=html_legend, position="topright") %>%
addLayersControl(position="topleft", overlayGroups = c("Graticule"),
options=layersControlOptions(collapsed=FALSE)) #%>%
# addMarkers(lng=-86.3, #input$user_long
# lat=30.25, #input$user_lat
# icon=boat_icon) #%>%
if (input$geolocation == TRUE) {
umap <- umap %>%
addMarkers(lng=input$long,
lat=input$lat,
icon=boat_icon) %>%
addControl(html=html_legend, position="topright")
}
if (nrow(userid_data()) >= 1) {
if (input$radio_points == "Species Encountered") {
umap <- umap %>%
clearGroup("Depredation Intensity") %>%
clearGroup("Current Intensity") %>%
addCircleMarkers(
data=userid_data(),
lng=~as.numeric(longitude),
lat=~as.numeric(latitude),
weight=3,
radius=10,
fillOpacity = opacity(),
color = ~colors_sp(species),
popup=~poppy,
group="Species Encountered"
) %>%
leaflet::addLegend(position = 'topright',
pal = colors_sp,
values = factor(c("None", "Shark", "Dolphin"), levels = c("None", "Shark", "Dolphin")),
opacity = 1,
title = HTML("Species Encountered"),
group = "Species Encountered",
layerId = "Species Encountered")
} else if (input$radio_points == "Depredation Intensity") {
umap <- umap %>%
clearGroup("Species Encountered") %>%
clearGroup("Current Intensity") %>%
addCircleMarkers(
data=userid_data(),
lng=~as.numeric(longitude),
lat=~as.numeric(latitude),
weight=3,
radius=10,
fillOpacity = opacity(),
color = ~pro_pal(depred),
popup=~poppy,
group="Depredation Intensity"
) %>%
addLegend(
position = 'topright',
pal = pro_pal,
values = factor(c("None", "Moderate", "High"), levels = c("None", "Moderate", "High")),
opacity = 1,
title = HTML("Depredation Intensity"),
group = "Depredation Intensity",
layerId = "Depredation Intensity")
} else if (input$radio_points == "Current Intensity") {
umap <- umap %>%
clearGroup("Depredation Intensity") %>%
clearGroup("Species Encountered") %>%
addCircleMarkers(
data=userid_data(),
lng=~as.numeric(longitude),
lat=~as.numeric(latitude),
weight=3,
radius=10,
fillOpacity = opacity(),
color = ~pro_pal(current),
popup=~poppy,
group="Current Intensity"
) %>%
addLegend(
position = 'topright',
pal = pro_pal,
values = factor(c("None", "Moderate", "High"), levels = c("None", "Moderate", "High")),
opacity = 1,
title = HTML("Current Intensity"),
group = "Current Intensity",
layerId = "Current Intensity")
}
}
return(umap)
})
} #end server