How do you loop through a SharedData object in order to plot separate addPolylines to a Leaflet map in R?
I have dataset with distinct "routes", and I add them one by one in a for
loop to not make them connected with each other. Next, I want them all to be responsive to a slider added by the Crosstalk
package, but I am having issues looping through the SharedData$new
object.
I have tried:
#Load libraries
library(dplyr); library(leaflet)
# An example of my data:
data <- data.frame(lon = c(12.42111, 12.42111, 12.41170, 12.42111, 12.39508, 12.39970, 12.42111, 12.39508),
lat = c(55.73615, 55.73615, 55.74155, 55.73615, 55.73074, 55.73871, 55.73615, 55.73074),
date = c("2020-03-28 12:46:29", "2020-03-28 13:20:42", "2020-03-28 13:50:47", "2020-03-28 18:33:44",
"2020-03-28 19:24:11", "2020-03-28 20:31:29", "2020-03-28 21:33:29", "2020-03-28 21:42:05"),
group = c(1, 1, 1, 1, 2, 2, 2, 2))
data$date <- as.POSIXct(data$date, format="%Y-%m-%d %H:%M:%S")
# Create leaflet map
temp_leaflet <- leaflet(data) %>% addTiles()
# for loop way of adding grouped routes
for (i in unique(factor(data$group))) {
temp_leaflet <- temp_leaflet %>%
addPolylines(data = data[data$group == i, ],
lng = ~lon, lat = ~lat, group = i)
}
temp_leaflet <- temp_leaflet %>%
hideGroup(unique(factor(data$group))) %>%
addLayersControl(
overlayGroups = unique(factor(data$group)),
options = layersControlOptions(collapsed = F))
So this is way I do it, but if I want to be able to change the two routes by time in a slider (date
column) with the Crosstalk
package, I simply can't figure out how to loop through a SharedData$new
object, and group it, so that it is hidden by default.
Any thoughts on how to achieve this end?