-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.qmd
More file actions
1534 lines (1351 loc) · 52.1 KB
/
Copy pathindex.qmd
File metadata and controls
1534 lines (1351 loc) · 52.1 KB
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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Mapa de riesgo de incendios"
subtitle: "AEMET OpenData · NASA FIRMS · EFFIS/Copernicus · GISCO/NUTS"
format:
html:
page-layout: full
toc: false
execute:
echo: false
warning: false
message: false
---
```{r setup}
library(leaflet)
library(htmltools)
library(htmlwidgets)
library(jsonlite)
library(readr)
library(dplyr)
library(purrr)
source("R/effis.R", encoding = "UTF-8")
source("R/admin.R", encoding = "UTF-8")
`%||%` <- function(x, y) {
if (is.null(x) || length(x) == 0 || all(is.na(x)) || !nzchar(paste(x, collapse = ""))) y else x
}
read_layers_json <- function() {
candidates <- c(
"data/processed/layers.json",
"assets/aemet/layers.json",
"docs/assets/aemet/layers.json"
)
for (path in candidates) {
if (file.exists(path) && file.info(path)$size > 2) {
layers <- tryCatch(
jsonlite::fromJSON(path, simplifyVector = FALSE),
error = function(e) list()
)
if (length(layers) > 0) {
attr(layers, "source_path") <- path
return(layers)
}
}
}
csv_path <- "data/processed/layers.csv"
if (file.exists(csv_path) && file.info(csv_path)$size > 0) {
layers_csv <- readr::read_csv(csv_path, show_col_types = FALSE)
if (nrow(layers_csv) > 0) {
layers <- layers_csv |>
mutate(
bounds = purrr::map(bounds_json, jsonlite::fromJSON),
legend_labels = strsplit(legend_labels, "\\|"),
legend_colours = strsplit(legend_colours, "\\|")
) |>
select(-bounds_json) |>
jsonlite::toJSON(dataframe = "rows", auto_unbox = TRUE, null = "null") |>
jsonlite::fromJSON(simplifyVector = FALSE)
attr(layers, "source_path") <- csv_path
return(layers)
}
}
layers <- list()
attr(layers, "source_path") <- NA_character_
layers
}
read_firms_csv <- function() {
candidates <- c(
"data/processed/firms_active_fires.csv",
"assets/firms/firms_active_fires.csv"
)
for (path in candidates) {
if (file.exists(path) && file.info(path)$size > 0) {
out <- tryCatch(
readr::read_csv(path, show_col_types = FALSE),
error = function(e) tibble::tibble()
)
if (nrow(out) > 0 && all(c("longitude", "latitude") %in% names(out))) {
attr(out, "source_path") <- path
return(out)
}
}
}
out <- tibble::tibble()
attr(out, "source_path") <- NA_character_
out
}
read_csv_optional <- function(paths) {
for (path in paths) {
if (file.exists(path) && file.info(path)$size > 0) {
out <- tryCatch(
readr::read_csv(path, show_col_types = FALSE),
error = function(e) tibble::tibble()
)
attr(out, "source_path") <- path
return(out)
}
}
out <- tibble::tibble()
attr(out, "source_path") <- NA_character_
out
}
read_dashboard_overview <- function() {
read_csv_optional(c(
"data/processed/dashboard_summary.csv",
"assets/summary/dashboard_summary.csv"
))
}
read_summary_ccaa <- function() {
read_csv_optional(c(
"data/processed/firms_summary_ccaa.csv",
"assets/summary/firms_summary_ccaa.csv"
))
}
read_summary_provincias <- function() {
read_csv_optional(c(
"data/processed/firms_summary_provincias.csv",
"assets/summary/firms_summary_provincias.csv"
))
}
read_territorial_summary <- function() {
candidates <- c(
"data/processed/territorial_summary.json",
"assets/summary/territorial_summary.json"
)
for (path in candidates) {
if (file.exists(path) && file.info(path)$size > 2) {
out <- tryCatch(
jsonlite::fromJSON(path, simplifyVector = FALSE),
error = function(e) NULL
)
if (!is.null(out)) {
attr(out, "source_path") <- path
return(out)
}
}
}
out <- list(
generated_at_utc = NA_character_,
methodology = list(),
ccaa = list(),
provincias = list()
)
attr(out, "source_path") <- NA_character_
out
}
read_operational_alerts <- function() {
read_csv_optional(c(
"data/processed/operational_alerts.csv",
"assets/alerts/operational_alerts.csv"
))
}
read_alerts_summary <- function() {
read_csv_optional(c(
"data/processed/operational_alerts_summary.csv",
"assets/alerts/operational_alerts_summary.csv"
))
}
safe_value <- function(x, default = "—") {
if (length(x) == 0 || is.na(x) || identical(x, "")) default else as.character(x)
}
add_admin_boundaries <- function(
map,
path,
group,
weight = 1,
colour = "#333333",
fill_opacity = 0.01
) {
if (!requireNamespace("sf", quietly = TRUE)) return(map)
if (!file.exists(path) || file.info(path)$size == 0) return(map)
x <- tryCatch(sf::st_read(path, quiet = TRUE), error = function(e) NULL)
if (is.null(x) || nrow(x) == 0) return(map)
x <- force_wgs84_lonlat(x)
if (!"admin_name" %in% names(x)) {
x$admin_name <- if ("NUTS_NAME" %in% names(x)) x$NUTS_NAME else x$admin_id
}
leaflet::addPolygons(
map,
data = x,
group = group,
layerId = ~paste(admin_level, admin_id, sep = ":"),
color = colour,
weight = weight,
opacity = 0.85,
fillColor = colour,
fillOpacity = fill_opacity,
label = ~paste0(admin_name, " · clic para consultar"),
highlightOptions = highlightOptions(
color = "#1676a3",
weight = weight + 1,
fillOpacity = 0.10,
bringToFront = TRUE
)
)
}
read_effis_ba_summary <- function() {
json_candidates <- c(
"assets/effis_ba/summary.json",
"docs/assets/effis_ba/summary.json"
)
for (path in json_candidates) {
if (file.exists(path) && file.info(path)$size > 2) {
out <- tryCatch(jsonlite::fromJSON(path, simplifyVector = TRUE), error = function(e) NULL)
if (!is.null(out)) {
attr(out, "source_path") <- path
return(out)
}
}
}
csv_path <- "data/processed/effis_burnt_areas_summary.csv"
if (file.exists(csv_path) && file.info(csv_path)$size > 0) {
out <- tryCatch(readr::read_csv(csv_path, show_col_types = FALSE), error = function(e) NULL)
if (!is.null(out) && nrow(out) > 0) {
out <- as.list(out[1, ])
attr(out, "source_path") <- csv_path
return(out)
}
}
out <- list(n_features = 0L, asset_geojson = "assets/effis_ba/effis_burnt_areas.geojson")
attr(out, "source_path") <- NA_character_
out
}
layers_data <- read_layers_json()
layers_source <- attr(layers_data, "source_path")
# Orden del selector AEMET en Leaflet.
# El paquete SIG clásico usa nombres down_YYYYMMDD...D00..D07,
# donde YYYYMMDD es la fecha civil del primer mapa y Dxx el horizonte.
# En el catálogo se guarda valid_date = issue_date + D.
aemet_valid_date_rank <- function(date_chr, today = Sys.Date()) {
d <- suppressWarnings(as.Date(date_chr))
if (is.na(d)) return(999999L)
if (!is.na(d) && d == today) return(0L)
if (d > today) return(as.integer(d - today))
10000L + as.integer(today - d)
}
aemet_layer_rank <- function(layer) {
area <- layer$area %||% ""
area_rank <- dplyr::case_when(
area == "p" ~ 1L,
area == "b" ~ 2L,
area == "c" ~ 3L,
TRUE ~ 99L
)
tipo <- layer$tipo %||% ""
tipo_rank <- dplyr::case_when(
tipo == "previsto" ~ 1L,
tipo == "estimado" ~ 2L,
TRUE ~ 99L
)
valid_date <- layer$valid_date %||% layer$date %||% ""
valid_rank <- aemet_valid_date_rank(valid_date)
dia <- suppressWarnings(as.integer(layer$dia %||% 0L))
if (is.na(dia)) dia <- 0L
issue_date <- layer$issue_date %||% ""
paste0(
sprintf("%02d", area_rank), "_",
sprintf("%06d", valid_rank), "_",
sprintf("%02d", tipo_rank), "_",
sprintf("%02d", dia), "_",
issue_date
)
}
if (length(layers_data) > 0) {
layers_data <- layers_data[order(vapply(layers_data, aemet_layer_rank, character(1)))]
}
n_layers <- length(layers_data)
layers_json <- jsonlite::toJSON(layers_data, auto_unbox = TRUE, null = "null")
last_update <- if (n_layers > 0) {
unique(vapply(layers_data, function(x) {
value <- x[["valid_date"]] %||% x[["date"]]
if (is.null(value) || length(value) == 0 || is.na(value)) NA_character_ else as.character(value)
}, character(1)))[1]
} else {
NA_character_
}
firms_data <- read_firms_csv()
firms_source <- attr(firms_data, "source_path")
n_firms <- nrow(firms_data)
overview_data <- read_dashboard_overview()
summary_ccaa <- read_summary_ccaa()
summary_provincias <- read_summary_provincias()
territorial_data <- read_territorial_summary()
territorial_source <- attr(territorial_data, "source_path")
territorial_json <- jsonlite::toJSON(
territorial_data,
auto_unbox = TRUE,
null = "null",
na = "null"
)
alerts_data <- read_operational_alerts()
alerts_summary <- read_alerts_summary()
effis_ba_summary <- read_effis_ba_summary()
effis_ba_source <- attr(effis_ba_summary, "source_path")
n_effis_ba <- suppressWarnings(as.integer(effis_ba_summary$n_features %||% 0L))
if (is.na(n_effis_ba)) n_effis_ba <- 0L
effis_ba_url <- as.character(effis_ba_summary$asset_geojson %||% "assets/effis_ba/effis_burnt_areas.geojson")
effis_ba_config_json <- jsonlite::toJSON(
list(
enabled = n_effis_ba > 0 && file.exists(effis_ba_url),
url = effis_ba_url,
n_features = n_effis_ba
),
auto_unbox = TRUE,
null = "null"
)
latest_layer_value <- function(layers, field) {
values <- vapply(layers, function(layer) {
value <- layer[[field]] %||% ""
if (length(value) == 0 || is.na(value)) "" else as.character(value)
}, character(1))
values <- values[nzchar(values)]
if (length(values) == 0) NA_character_ else max(values)
}
first_overview_value <- function(data, field) {
if (nrow(data) == 0 || !field %in% names(data)) return(NA_character_)
value <- data[[field]][1]
if (length(value) == 0 || is.na(value) || !nzchar(as.character(value))) NA_character_ else as.character(value)
}
freshness_config_json <- jsonlite::toJSON(
list(
aemet_issue_date = latest_layer_value(layers_data, "issue_date"),
firms_latest_detection_utc = first_overview_value(overview_data, "ultima_deteccion_utc"),
firms_generated_at_utc = first_overview_value(overview_data, "generated_at_utc"),
effis_generated_at_utc = as.character(effis_ba_summary$generated_at %||% NA_character_),
effis_max_date = as.character(effis_ba_summary$max_date %||% NA_character_)
),
auto_unbox = TRUE,
null = "null",
na = "null"
)
if (nrow(overview_data) > 0) {
overview <- overview_data[1, ]
} else {
overview <- tibble::tibble(
n_firms = n_firms,
n_firms_6h = if (n_firms > 0 && "age_hours" %in% names(firms_data)) sum(!is.na(firms_data$age_hours) & firms_data$age_hours <= 6) else 0L,
n_firms_24h = if (n_firms > 0 && "age_hours" %in% names(firms_data)) sum(!is.na(firms_data$age_hours) & firms_data$age_hours <= 24) else 0L,
frp_total_mw = if (n_firms > 0 && "frp" %in% names(firms_data)) round(sum(as.numeric(firms_data$frp), na.rm = TRUE), 1) else 0,
ultima_deteccion_utc = NA_character_,
n_ccaa_con_focos = nrow(summary_ccaa),
n_provincias_con_focos = nrow(summary_provincias)
)
}
effis_groups <- effis_overlay_groups()
effis_cfg <- effis_layer_config()
n_alerts <- nrow(alerts_data)
n_alerts_high <- if (n_alerts > 0 && "alerta_operativa" %in% names(alerts_data)) sum(alerts_data$alerta_operativa == "alta", na.rm = TRUE) else 0L
n_alerts_medium <- if (n_alerts > 0 && "alerta_operativa" %in% names(alerts_data)) sum(alerts_data$alerta_operativa == "media", na.rm = TRUE) else 0L
```
## Mapa
```{r fire-map}
#| column: screen-inset
base_groups <- c("Base clara", "Satélite")
overlay_groups <- character()
map <- leaflet(width = "100%", height = "88vh", options = leafletOptions(preferCanvas = TRUE, zoomControl = TRUE)) |>
addProviderTiles(providers$CartoDB.Positron, group = "Base clara") |>
addProviderTiles(providers$Esri.WorldImagery, group = "Satélite") |>
setView(lng = -3.7, lat = 40.2, zoom = 6)
# Panes: AEMET queda por debajo; EFFIS BA en medio; FIRMS/alertas por encima.
map <- map |>
addMapPane("aemetPane", zIndex = 350) |>
addMapPane("effisBaPane", zIndex = 520) |>
addMapPane("firmsPane", zIndex = 650) |>
addMapPane("alertsPane", zIndex = 670)
if (n_effis_ba > 0 && file.exists(effis_ba_url)) {
# Marcador transparente para registrar el grupo en el control Leaflet. La
# geometría EFFIS se descarga desde JavaScript solo cuando se activa la capa.
map <- map |>
addCircleMarkers(
lng = 0,
lat = 0,
group = "EFFIS Burnt Areas",
radius = 0,
stroke = FALSE,
fillOpacity = 0,
options = pathOptions(pane = "effisBaPane", interactive = FALSE)
)
overlay_groups <- c(overlay_groups, "EFFIS Burnt Areas")
}
if (n_firms > 0) {
firms_data <- firms_data |>
mutate(
age_hours = suppressWarnings(as.numeric(age_hours)),
frp = suppressWarnings(as.numeric(frp))
)
if (!"popup_label" %in% names(firms_data)) {
firms_data <- firms_data |>
mutate(
popup_label = paste0(
"NASA FIRMS<br>",
"Sensor: ", source_dataset, "<br>",
"Fecha UTC: ", acq_datetime_utc, "<br>",
"FRP: ", ifelse(is.na(frp), "s/d", paste0(frp, " MW"))
)
)
}
firms_data <- firms_data |>
mutate(
firms_colour = case_when(
is.na(age_hours) ~ "#666666",
age_hours <= 6 ~ "#d7191c",
age_hours <= 24 ~ "#fdae61",
age_hours <= 48 ~ "#ffffbf",
TRUE ~ "#999999"
),
firms_radius = pmax(4, pmin(10, ifelse(is.na(frp), 5, sqrt(frp) + 3))),
popup = popup_label
)
map <- map |>
addCircleMarkers(
data = firms_data,
lng = ~longitude,
lat = ~latitude,
group = "NASA FIRMS - focos activos",
radius = ~firms_radius,
color = ~firms_colour,
fillColor = ~firms_colour,
fillOpacity = 0.82,
weight = 1,
popup = ~popup,
label = ~paste0("FIRMS · ", acq_datetime_utc),
options = pathOptions(pane = "firmsPane")
)
overlay_groups <- c(overlay_groups, "NASA FIRMS - focos activos")
}
if (n_alerts > 0) {
if (!"popup_label" %in% names(alerts_data)) {
alerts_data <- alerts_data |>
mutate(popup_label = paste0(cluster_id, "<br>Nivel: ", alerta_operativa))
}
alerts_data <- alerts_data |>
mutate(
longitude = suppressWarnings(as.numeric(longitude)),
latitude = suppressWarnings(as.numeric(latitude)),
score = suppressWarnings(as.numeric(score)),
alert_colour = case_when(
alerta_operativa == "alta" ~ "#7b3294",
alerta_operativa == "media" ~ "#d7191c",
alerta_operativa == "seguimiento" ~ "#fdae61",
TRUE ~ "#666666"
),
alert_radius = pmax(7, pmin(16, sqrt(pmax(1, score)) + 5)),
popup = as.character(popup_label)
) |>
filter(!is.na(longitude), !is.na(latitude))
if (nrow(alerts_data) > 0) {
map <- map |>
addCircleMarkers(
data = alerts_data,
lng = ~longitude,
lat = ~latitude,
group = "Alertas operativas FIRMS",
radius = ~alert_radius,
color = ~alert_colour,
fillColor = ~alert_colour,
fillOpacity = 0.42,
weight = 3,
popup = ~popup,
label = ~paste0(cluster_id, " · ", alerta_operativa),
options = pathOptions(pane = "alertsPane")
)
overlay_groups <- c(overlay_groups, "Alertas operativas FIRMS")
}
}
map <- add_effis_wms_layers(map)
overlay_groups <- c(overlay_groups, effis_groups)
map <- map |>
add_admin_boundaries(
"data/processed/admin_nuts2_ccaa.geojson",
"CCAA (NUTS2)",
weight = 1.2,
colour = "#2b5d87",
fill_opacity = 0.015
) |>
add_admin_boundaries(
"data/processed/admin_nuts3_provincias.geojson",
"Provincias (NUTS3)",
weight = 0.7,
colour = "#555555",
fill_opacity = 0.01
)
overlay_groups <- c(overlay_groups, "CCAA (NUTS2)", "Provincias (NUTS3)")
# Las CCAA quedan visibles para habilitar la consulta territorial directa.
# Las provincias continúan siendo opcionales desde el control de capas.
hidden_groups <- intersect(
c(effis_groups, "EFFIS Burnt Areas", "Provincias (NUTS3)"),
unique(overlay_groups)
)
map <- map |>
addScaleBar(position = "bottomleft") |>
addLayersControl(
baseGroups = base_groups,
overlayGroups = unique(overlay_groups),
options = layersControlOptions(collapsed = TRUE)
)
if (length(hidden_groups) > 0) {
map <- hideGroup(map, hidden_groups)
}
map <- map |>
addControl(
html = HTML(
"Fuentes: AEMET OpenData · NASA FIRMS · EFFIS/Copernicus EMS · Eurostat/GISCO<br>
Visor informativo; no sustituye a avisos oficiales ni a servicios de emergencia."
),
position = "bottomleft"
)
if (n_firms > 0) {
map <- map |>
addControl(
html = HTML(
"<b>NASA FIRMS</b><br>
<span style='color:#d7191c'>●</span> < 6 h<br>
<span style='color:#fdae61'>●</span> 6–24 h<br>
<span style='color:#bdb76b'>●</span> 24–48 h<br>
<span style='color:#999999'>●</span> > 48 h<br>
<b>Alertas</b><br>
<span style='color:#7b3294'>●</span> alta<br>
<span style='color:#d7191c'>●</span> media"
),
position = "bottomright"
)
}
js_template <- r"(
function(el, x) {
const layers = __LAYERS_JSON__;
const effisBurntAreas = __EFFIS_BA_CONFIG__;
const freshness = __FRESHNESS_CONFIG__;
const territorial = __TERRITORIAL_DATA__;
const map = this;
if (map.createPane && !map.getPane('aemetPane')) {
map.createPane('aemetPane');
map.getPane('aemetPane').style.zIndex = 350;
map.getPane('aemetPane').style.pointerEvents = 'none';
}
let currentOverlay = null;
let currentOpacity = 0.68;
let effisBaLayer = null;
let effisBaData = null;
let effisBaVisible = false;
let currentLayerIndex = 0;
let currentLayerRequest = 0;
let playbackTimer = null;
let selectedTerritory = null;
let selectedTerritoryLayer = null;
let territoryPanelRequest = 0;
const adminLayersByKey = new Map();
const aemetImageCache = new Map();
const playbackIntervalMs = 1800;
function escapeHtml(value) {
return String(value === null || value === undefined ? '' : value)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function effisPopup(properties) {
const p = properties || {};
const rows = [
['ID', p.effis_id || p.id],
['Fecha', p.effis_date || p.FIREDATE],
['Superficie', p.effis_area_ha !== undefined ? (p.effis_area_ha + ' ha') : p.AREA_HA],
['País', p.COUNTRY || p.country]
].filter(row => row[1] !== null && row[1] !== undefined && row[1] !== '');
return '<strong>EFFIS Burnt Area</strong>' + rows.map(row => '<br>' + escapeHtml(row[0]) + ': ' + escapeHtml(row[1])).join('');
}
function addEffisBurntAreas() {
if (!effisBurntAreas || !effisBurntAreas.enabled || !effisBurntAreas.url) return;
effisBaVisible = true;
const attachLayer = function(data) {
if (!effisBaVisible) return;
if (effisBaLayer) map.removeLayer(effisBaLayer);
effisBaLayer = L.geoJSON(data, {
pane: 'effisBaPane',
style: {
color: '#5e3c99',
weight: 1.1,
opacity: 0.9,
fillColor: '#fdb863',
fillOpacity: 0.28
},
onEachFeature: function(feature, layer) {
layer.bindPopup(effisPopup(feature.properties || {}));
layer.bindTooltip('EFFIS Burnt Area');
}
}).addTo(map);
};
if (effisBaData) {
attachLayer(effisBaData);
return;
}
fetch(effisBurntAreas.url)
.then(response => {
if (!response.ok) throw new Error('HTTP ' + response.status);
return response.json();
})
.then(data => {
effisBaData = data;
attachLayer(data);
})
.catch(error => console.error('No se pudo cargar EFFIS Burnt Areas:', error));
}
function removeEffisBurntAreas() {
effisBaVisible = false;
if (effisBaLayer) {
map.removeLayer(effisBaLayer);
effisBaLayer = null;
}
}
map.on('overlayadd', function(event) {
if (event && event.name === 'EFFIS Burnt Areas') addEffisBurntAreas();
if (event && event.layer) attachTerritoryLayer(event.layer);
});
map.on('overlayremove', function(event) {
if (event && event.name === 'EFFIS Burnt Areas') removeEffisBurntAreas();
});
function capitaliseFirst(value) {
const text = String(value || '');
return text ? text.charAt(0).toUpperCase() + text.slice(1) : '';
}
function parseIsoDateUtc(value) {
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(value || ''));
if (!match) return null;
const date = new Date(Date.UTC(
parseInt(match[1], 10),
parseInt(match[2], 10) - 1,
parseInt(match[3], 10)
));
return Number.isNaN(date.getTime()) ? null : date;
}
function formatAemetDate(value) {
const date = parseIsoDateUtc(value);
if (!date) return String(value || 'Fecha no disponible');
const formatted = new Intl.DateTimeFormat('es-ES', {
weekday: 'long',
day: 'numeric',
month: 'long',
year: 'numeric',
timeZone: 'UTC'
}).format(date);
return capitaliseFirst(formatted);
}
function layerForecastLabel(layer) {
return (layer.forecast_label !== null && layer.forecast_label !== undefined && layer.forecast_label !== '')
? layer.forecast_label
: ((layer.dia === null || layer.dia === undefined || layer.dia === '') ? 'Hoy' : ('D+' + layer.dia));
}
function labelForLayer(layer) {
const dia = layerForecastLabel(layer);
const tipo = layer.tipo === 'estimado' ? 'Estimado' : 'Previsto';
const validDate = layer.valid_date || layer.date || '';
const issueDate = layer.issue_date || '';
const issueTxt = (issueDate && issueDate !== validDate) ? (' · emitido ' + formatAemetDate(issueDate)) : '';
return formatAemetDate(validDate) + ' · ' + layer.area_label + ' · ' + tipo + ' · ' + dia + issueTxt;
}
function updateLegend(layer) {
const legend = document.getElementById('fire-risk-legend');
if (!legend) return;
if (!layer || !layer.legend_labels || !layer.legend_colours) {
legend.innerHTML = '<b>Nivel de peligro AEMET</b><br>No disponible';
return;
}
const validDate = layer.valid_date || layer.date || '';
const dia = layerForecastLabel(layer);
const tipo = layer.tipo === 'estimado' ? 'Estimado' : 'Previsto';
let html = '<b>Nivel de peligro AEMET</b>';
html += '<div class="fire-legend-context">' +
escapeHtml(formatAemetDate(validDate)) + ' · ' + escapeHtml(dia) + '<br>' +
escapeHtml(layer.area_label || '') + ' · ' + escapeHtml(tipo) +
'</div>';
for (let i = 0; i < layer.legend_labels.length; i++) {
html += '<br><span class="swatch" style="background:' + escapeHtml(layer.legend_colours[i]) + '"></span> ' + escapeHtml(layer.legend_labels[i]);
}
legend.innerHTML = html;
}
function layerSeriesKey(layer) {
if (!layer) return '';
return [layer.area || '', layer.tipo || '', layer.issue_date || ''].join('|');
}
function seriesIndices(index) {
const layer = layers[index];
const key = layerSeriesKey(layer);
return layers
.map((candidate, candidateIndex) => ({candidate, candidateIndex}))
.filter(item => layerSeriesKey(item.candidate) === key)
.sort((a, b) => {
const dateA = a.candidate.valid_date || a.candidate.date || '';
const dateB = b.candidate.valid_date || b.candidate.date || '';
if (dateA !== dateB) return dateA.localeCompare(dateB);
return Number(a.candidate.forecast_day || a.candidate.dia || 0) - Number(b.candidate.forecast_day || b.candidate.dia || 0);
})
.map(item => item.candidateIndex);
}
function updateTimelineControls() {
const select = document.getElementById('fire-layer-select');
const previous = document.getElementById('fire-layer-previous');
const next = document.getElementById('fire-layer-next');
const position = document.getElementById('fire-layer-position');
const sequence = seriesIndices(currentLayerIndex);
const sequencePosition = sequence.indexOf(currentLayerIndex);
if (select) select.value = String(currentLayerIndex);
if (previous) previous.disabled = sequencePosition <= 0;
if (next) next.disabled = sequencePosition < 0 || sequencePosition >= sequence.length - 1;
if (position) position.textContent = sequencePosition >= 0 ? ((sequencePosition + 1) + ' de ' + sequence.length) : '—';
}
function stopPlayback() {
if (playbackTimer !== null) {
window.clearInterval(playbackTimer);
playbackTimer = null;
}
const button = document.getElementById('fire-layer-play');
if (button) {
button.innerHTML = '▶';
button.title = 'Reproducir la secuencia temporal';
button.setAttribute('aria-label', 'Reproducir la secuencia temporal');
button.classList.remove('is-playing');
}
}
function stepLayer(delta, wrap) {
const sequence = seriesIndices(currentLayerIndex);
if (sequence.length === 0) return;
let position = sequence.indexOf(currentLayerIndex);
if (position < 0) position = 0;
let target = position + delta;
if (wrap) target = (target + sequence.length) % sequence.length;
if (target < 0 || target >= sequence.length) return;
setLayer(sequence[target]);
}
function togglePlayback() {
if (playbackTimer !== null) {
stopPlayback();
return;
}
const sequence = seriesIndices(currentLayerIndex);
if (sequence.length <= 1) return;
const button = document.getElementById('fire-layer-play');
if (button) {
button.innerHTML = '❚❚';
button.title = 'Pausar la secuencia temporal';
button.setAttribute('aria-label', 'Pausar la secuencia temporal');
button.classList.add('is-playing');
}
playbackTimer = window.setInterval(function() {
stepLayer(1, true);
}, playbackIntervalMs);
}
function parseUtcTimestamp(value) {
let text = String(value || '').trim();
if (!text) return null;
if (/^\d{4}-\d{2}-\d{2}$/.test(text)) text += 'T00:00:00Z';
text = text.replace(/^(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2})/, '$1T$2');
text = text.replace(/([+-]\d{2})(\d{2})$/, '$1:$2');
const date = new Date(text);
return Number.isNaN(date.getTime()) ? null : date;
}
function madridDateKey(date) {
const parts = new Intl.DateTimeFormat('en-CA', {
timeZone: 'Europe/Madrid', year: 'numeric', month: '2-digit', day: '2-digit'
}).formatToParts(date);
const values = {};
parts.forEach(part => { if (part.type !== 'literal') values[part.type] = part.value; });
return [values.year, values.month, values.day].join('-');
}
function calendarAgeDays(isoDate) {
if (!/^\d{4}-\d{2}-\d{2}$/.test(String(isoDate || ''))) return null;
const today = madridDateKey(new Date());
const start = parseIsoDateUtc(isoDate);
const end = parseIsoDateUtc(today);
if (!start || !end) return null;
return Math.floor((end.getTime() - start.getTime()) / 86400000);
}
function relativeAge(date) {
if (!date) return 'sin fecha';
const minutes = Math.max(0, Math.round((Date.now() - date.getTime()) / 60000));
if (minutes < 60) return 'hace ' + minutes + ' min';
const hours = Math.round(minutes / 60);
if (hours < 48) return 'hace ' + hours + ' h';
return 'hace ' + Math.round(hours / 24) + ' días';
}
function freshnessRow(source, text, status, title) {
return '<div class="freshness-row freshness-' + status + '" title="' + escapeHtml(title || text) + '">' +
'<span class="freshness-dot" aria-hidden="true"></span>' +
'<span><strong>' + escapeHtml(source) + '</strong> · ' + escapeHtml(text) + '</span>' +
'</div>';
}
function updateFreshnessIndicator() {
const container = document.getElementById('data-freshness');
if (!container) return;
let html = '<div class="freshness-title">Actualidad de datos</div>';
const aemetDays = calendarAgeDays(freshness && freshness.aemet_issue_date);
if (aemetDays === null) {
html += freshnessRow('AEMET', 'sin fecha de emisión', 'unavailable');
} else if (aemetDays <= 0) {
html += freshnessRow('AEMET', 'emitido hoy', 'fresh', formatAemetDate(freshness.aemet_issue_date));
} else if (aemetDays === 1) {
html += freshnessRow('AEMET', 'emitido ayer', 'warning', formatAemetDate(freshness.aemet_issue_date));
} else {
html += freshnessRow('AEMET', 'emitido hace ' + aemetDays + ' días', 'stale', formatAemetDate(freshness.aemet_issue_date));
}
const firmsDate = parseUtcTimestamp(freshness && freshness.firms_latest_detection_utc);
if (!firmsDate) {
html += freshnessRow('FIRMS', 'sin detecciones disponibles', 'unavailable');
} else {
const firmsHours = Math.max(0, (Date.now() - firmsDate.getTime()) / 3600000);
const firmsStatus = firmsHours <= 6 ? 'fresh' : (firmsHours <= 24 ? 'warning' : 'stale');
html += freshnessRow('FIRMS', 'última detección ' + relativeAge(firmsDate), firmsStatus, firmsDate.toLocaleString('es-ES', {timeZone: 'Europe/Madrid'}));
}
const effisDate = parseUtcTimestamp(freshness && freshness.effis_generated_at_utc);
if (!effisDate) {
html += freshnessRow('EFFIS', 'sin actualización disponible', 'unavailable');
} else {
const effisHours = Math.max(0, (Date.now() - effisDate.getTime()) / 3600000);
const effisStatus = effisHours <= 24 ? 'fresh' : (effisHours <= 72 ? 'warning' : 'stale');
html += freshnessRow('EFFIS', 'actualizado ' + relativeAge(effisDate), effisStatus, effisDate.toLocaleString('es-ES', {timeZone: 'Europe/Madrid'}));
}
container.innerHTML = html;
}
function normaliseTerritoryLevel(value) {
const level = String(value || '').toLowerCase();
if (level === 'provincia' || level === 'provincias') return 'provincia';
return 'ccaa';
}
function territoryKey(level, adminId) {
return normaliseTerritoryLevel(level) + '|' + String(adminId || '');
}
function territoryRows(level) {
if (!territorial) return [];
return normaliseTerritoryLevel(level) === 'provincia'
? (territorial.provincias || [])
: (territorial.ccaa || []);
}
function adminPropertiesFromLayer(layer) {
if (layer && layer.feature && layer.feature.properties) {
return layer.feature.properties;
}
const layerId = layer && layer.options ? String(layer.options.layerId || '') : '';
const parts = layerId.split(':');
if (parts.length >= 2) {
return {
admin_level: parts[0],
admin_id: parts.slice(1).join(':')
};
}
return null;
}
function findTerritoryRecord(properties) {
const p = properties || {};
const level = normaliseTerritoryLevel(p.admin_level);
const id = String(p.admin_id || p.NUTS_ID || '');
return territoryRows(level).find(row => String(row.admin_id || '') === id) || {
admin_level: level,
admin_id: id,
admin_name: p.admin_name || p.NUTS_NAME || id,
representative_lon: null,
representative_lat: null,
n_focos: 0,
n_ultimas_6h: 0,
n_ultimas_12h: 0,
n_ultimas_24h: 0,
n_ultimas_48h: 0,
frp_total_mw: 0,
frp_media_mw: 0,
frp_max_mw: 0,
n_effis_30d: 0,
effis_area_ha_30d: 0,
n_effis_90d: 0,
effis_area_ha_90d: 0,
alerta_operativa: 'sin actividad'
};
}
function numberValue(value, fallback) {
const n = Number(value);
return Number.isFinite(n) ? n : (fallback === undefined ? 0 : fallback);
}
function formatMetric(value, digits) {
const n = Number(value);
if (!Number.isFinite(n)) return '—';
return new Intl.NumberFormat('es-ES', {
minimumFractionDigits: digits || 0,
maximumFractionDigits: digits || 0
}).format(n);
}
function formatTerritoryDateTime(value) {