-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.R
397 lines (308 loc) · 10.5 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
# source("global.R")
# input <- list(variable = "temp_promedio_aire", group = "Semanal", stat = "Promedio", station = 20, opt_yrsdata = c(2021, 2022))
function(input, output, session) {
data_estaciones <- tbl(pool, parametros$tabla_datos)
# main --------------------------------------------------------------------
# mapa principal
output$map <- renderLeaflet({
leaflet(
options = leafletOptions(
attributionControl = FALSE,
zoomControl = FALSE
)
) |>
addProviderTiles(providers$CartoDB.Positron, group = "Administrativo") |>
addProviderTiles(providers$Esri.WorldImagery, group = "Satélite") |>
addProviderTiles(providers$Esri.WorldTopoMap, group = "Topográfico") |>
addLayersControl(
baseGroups = c("Administrativo", "Satélite", "Topográfico"),
position = "bottomright",
options = layersControlOptions(collapsed = FALSE)
) |>
htmlwidgets::onRender("function(el, x) { L.control.zoom({ position: 'topright' }).addTo(this) }") |>
setView(lng = -70.64827, lat = -33.45694, zoom = 5) |>
leafem::addLogo(
# https://github.com/r-spatial/leafem/issues/16#issuecomment-1560516396
img = "https://raw.githubusercontent.com/ODES-Chile/odes-unidades-shiny-app/main/www/logo.png",
src= "remote",
position = "bottomleft",
offset.x = 15,
offset.y = 5,
) |>
# leaflet.extras::addSearchOSM(
# options = leaflet.extras::searchOptions(
# textErr = "Ubicación no encontrada",
# textCancel = "Cancelar",
# textPlaceholder = "Buscar...",
# position = "bottomright"
# )
# ) |>
addEasyButton(
easyButton(
position = "bottomright",
icon = "fa-crosshairs",
title = "Mi ubicación",
onClick = JS("function(btn, map){ map.locate({setView: true}); }")
)
)
})
# mini grafico
output$chart <- renderHighchart(hc_void)
# grafico temperatura estracion
# output$chart_temp <- renderHighchart(hc_void)
# botton cambia a detalle de la estación
observeEvent(input$detalle_estacion, {
message("hola, borrame plz")
nav_select(
id = "nav",
selected = "estacion",
session
)
})
# reactivo de informacion de variable seleccionada
data_variable <- reactive({
nmvar <- names(opt_variable[opt_variable == input$variable])
nmvar <- nmvar |>
str_split(" ") |>
unlist() |>
first()
data_variable <- ddefvars |>
filter(str_detect(Description, nmvar)) |>
slice(1) |>
# filter(Name == input$variable) |>
gather(k, v) |>
deframe()
data_variable
})
# data que depende de la variable/agrupacion/stats
# para todas las estaciones
data_transformada <- reactive({
cli::cli_h2("Start `data_transformada`")
# # aca el proceso se demora por lo que debiera...
if(input$showchart){
highchartProxy("chart") |>
hcpxy_loading(action = "show")
}
fceil <- fun_group[[input$group]]
fstat <- fun_stat[[input$stat]]
minyr <- min(input$opt_yrsdata)
maxyr <- max(input$opt_yrsdata)
data_transformada <- data_estaciones |>
filter(year(fecha_hora) <= maxyr) |>
filter(minyr <= year(fecha_hora)) |>
select(
fecha_hora,
valor = .data[[input$variable]],
station_id
) |>
collect()
# si no hay quea grupar, se retorna data sin procesar
if(identical(fceil, identity)) return(data_transformada)
data_transformada <- data_transformada |>
# redondeamos fechas
mutate(fecha_hora = fceil(fecha_hora)) |>
# agrupación
group_by(fecha_hora, station_id) |>
# calculo, por defaul, de momento obtendremos media
summarise(valor = fstat(valor), .groups = "drop") |>
ungroup()
cli::cli_h2("End `data_transformada`")
data_transformada
}) |>
bindCache(input$group, input$stat, input$variable, input$opt_yrsdata)
# filtra data_transformada por la estacion
# para el mini chart
data_transformada_estacion <- reactive({
data_transformada <- data_transformada()
data_transformada_estacion <- data_transformada |>
filter(station_id == input$station)
data_transformada_estacion
})
# data de estacion
# data_estacion <- reactive({
#
# data_estacion <- data |>
# filter(estacion_id == input$station)
#
# data_estacion
#
# })
# filtra data_transformada por el ultimo registro
data_markers <- reactive({
data_transformada <- data_transformada()
data_markers <- data_transformada |>
group_by(station_id) |>
filter(fecha_hora == max(fecha_hora)) |>
ungroup() |>
left_join(
select(destaciones, latitud, longitud, station_id, nombre_estacion, red),
by = "station_id"
)
data_markers
})
# observer que mira si variable es precipitacion
observeEvent(input$variable, {
if(input$variable == "precipitacion_horaria") {
opts <- "Acumulado (suma)"
} else {
opts <- setdiff(opt_stat, "Acumulado (suma)")
}
updateSelectInput(session = session, "stat", choices = opts)
})
# observer escucha variable y valor para modificar estaciones/markers
observe({
# message(input$variable)
# colorBy <- input$variable
# sizeBy <- input$size
data_markers <- data_markers()
data_variable <- data_variable()
# crear label
data_markers <- data_markers |>
mutate(
# spark = map_chr(valor, function(x){ as.character(htmltools::tagList(sparkline(sample(20), width = 100))) }),
lbl = str_glue("{ nombre_estacion }:<br/> {round(valor, 2)} { data_variable$Symbol }<br/><small>red: { red }</small>")
)
colorData <- data_markers[["valor"]]
pal <- colorBin(data_variable$cols, colorData, 10, pretty = TRUE)
leafletProxy("map") |>
clearShapes() |>
# leaflet() |>
# addTiles() |>
# provider
# addCircles(
addCircleMarkers(
data = data_markers,
~longitud,
~latitud,
stroke = TRUE,
color = "white",
weight = 1,
clusterOptions = markerClusterOptions(), # agrupando estaciones
# radius = radius,
# https://stackoverflow.com/a/43155126/829971
label = ~lapply(data_markers$lbl, htmltools::HTML),
# label = ~htmltools::htmlEscape(lbl),
labelOptions = labelOptions(
# offset = c(-20, -20),
style = list(
"font-family" = parametros$font_family,
"box-shadow" = "2px 2px rgba(0,0,0,0.15)",
"font-size" = "15px",
"padding" = "15px",
"border-color" = "rgba(0,0,0,0.15)"
)
),
layerId = ~station_id,
fillOpacity = 0.95,
fillColor = pal(colorData)
) |>
addLegend(
# "bottomleft",
"topright",
pal = pal,
na.label = "No disponible",
values = colorData,
title = data_variable$Symbol,
# labFormat = labelFormat(suffix = ),
layerId = "colorLegend"
)
})
# observer que ve en que estación se hace click y cambia
# el selector de estaciones "station"
# observeEvent(input$map_shape_click, {
observeEvent(input$map_marker_click, {
print(input$map_shape_click)
print(input$map_marker_click)
updateSelectizeInput(
session,
inputId = "station",
selected = input$map_marker_click$id
)
})
# dado el cambio de estacion:
# 1. centrar el mapa en la ubicación de la estacion
observeEvent(input$station, {
# message(input$station)
if(input$station == "") return(TRUE)
# leaflet
coords <- destaciones |>
filter(station_id == input$station) |>
select(longitud, latitud) |>
gather() |>
deframe() |>
as.list()
leafletProxy("map") |>
setView(lng = coords$longitud, lat = coords$latitud, zoom = input$map_zoom)
})
# observa si cambia la data estacion para modificar el mini chart
observe({
if(!input$showchart) return(TRUE)
data_transformada_estacion <- data_transformada_estacion()
data_variable <- data_variable()
datos <- data_transformada_estacion |>
select(x = fecha_hora, y = valor) |>
mutate(x = datetime_to_timestamp(x), y = round(y, 2)) |>
arrange(x)
typechart <- ifelse(str_detect(data_variable$Description, "Precipi"), "column", "spline")
highchartProxy("chart") |>
hcpxy_update_series(
id = "data",
lineWidth = 1,
type = typechart,
states = list(hover = list(lineWidthPlus = 0)),
data = list_parse2(datos),
color = parametros$color,
name = data_variable$Description
) |>
hcpxy_update(
# tooltip = list(),
yAxis = list(
labels = list(
format = str_glue("{{value}} { symbol }", symbol = data_variable$Symbol)
)
),
credits = list(text = data_variable$Description)
) |>
hcpxy_loading(action = "hide") |>
hcpxy_update_series()
})
# salon -------------------------------------------------------------------
output$chart_nyt <- renderHighchart({
nyt_chart(input$station_nyt, input$salon_yrs)
})
output$chart_chi <- renderHighchart({
hcmap("countries/cl/cl-all")
})
# datos -------------------------------------------------------------------
station_data <- reactive({
sttns <- isolate(input$station_data_stations)
# sttns <- c(4, 10)
dts <- isolate(input$station_data_date)
# dts <- tail(opt_estaciones_meses, 2)
dts <- lubridate::ymd(str_c(dts, "/01", sep = ""))
dts_min <- lubridate::as_datetime(dts[1])
dts_max <- lubridate::as_datetime(dts[2]) + months(1) - lubridate::seconds(1)
data_estaciones |>
filter(station_id %in% sttns) |>
filter(fecha_hora <= dts_max) |>
filter(dts_min >= dts_min) |>
collect()
})
output$station_data_download <- downloadHandler(
filename = function() {
paste("data-", Sys.Date(), ".csv", sep="")
},
content = function(file) {
write.csv(station_data(), file)
}
)
# opciones ----------------------------------------------------------------
# mapa demo
output$map_demo <- renderLeaflet({
map <- leaflet(options = leafletOptions(zoomControl = FALSE)) |>
setView(lng = -70.64827, lat = -33.45694, zoom = 6) |>
addProviderTiles(input$leafletprov) |>
htmlwidgets::onRender("function(el, x) { L.control.zoom({ position: 'topright' }).addTo(this) }")
map
})
}