In the code below, I am trying to use the leaftime package to make a map with a time slider. The idea is to color the countries/regions as the time moves from start date to end date. In addition, I would like the names of the countries (from the column Country) to pop up as labels while hovering over them (after it has been colored). I have looked online, and the examples I find mainly describe how to do this for point data (using the poinToLayer). I would appreciate any ideas how to implement this for polygon or multipolygon layers.
library(sf)
library(leaflet)
library(leaftime)
`# Creating base data frame with spatial polygons and country names`
power <- data.frame(
"Country" = c("Germany", "Spain", "United Kingdom", "Italy", "United States",
"Thailand", "Singapore", "Japan", "France", "Australia"),
"start" = seq.Date(as.Date("2015-01-01"), by = "day", length.out = 10),
"end" = rep(as.Date("2015-01-10"), 10)
)
`# Sample polygons (WKT format) for 10 countries (simplified)`
country_polygons <- c(
"POLYGON ((13.0 52.0, 13.1 52.0, 13.1 52.1, 13.0 52.1, 13.0 52.0))", # Germany
"POLYGON ((-3.0 40.0, -3.1 40.0, -3.1 40.1, -3.0 40.1, -3.0 40.0))", # Spain
"POLYGON ((-0.1 51.5, 0.0 51.5, 0.0 51.6, -0.1 51.6, -0.1 51.5))", # UK
"POLYGON ((12.0 41.9, 12.1 41.9, 12.1 42.0, 12.0 42.0, 12.0 41.9))", # Italy
"POLYGON ((-74.0 40.7, -74.1 40.7, -74.1 40.8, -74.0 40.8, -74.0 40.7))", # USA
"POLYGON ((100.5 13.7, 100.6 13.7, 100.6 13.8, 100.5 13.8, 100.5 13.7))", # Thailand
"POLYGON ((103.8 1.3, 103.9 1.3, 103.9 1.4, 103.8 1.4, 103.8 1.3))", # Singapore
"POLYGON ((139.7 35.6, 139.8 35.6, 139.8 35.7, 139.7 35.7, 139.7 35.6))", # Japan
"POLYGON ((2.3 48.8, 2.4 48.8, 2.4 48.9, 2.3 48.9, 2.3 48.8))", # France
"POLYGON ((144.9 -37.8, 145.0 -37.8, 145.0 -37.7, 144.9 -37.7, 144.9 -37.8))" # Australia
)
`# Converting polygons to sf objects`
power$geometry <- st_as_sfc(country_polygons, crs = 4326)
`# Converting the data frame to an sf object`
power_sf <- st_as_sf(power, sf_column_name = "geometry")
`# Adding the timeline to the leaflet map with country labels using the JS function`
leaflet_map %>%
addTimeline( data=x,
sliderOpts = sliderOptions(
formatOutput = htmlwidgets::JS(
"function(date) {return new Date(date).toDateString()}
"),
position = "bottomright",
step = 50,
duration = 3000,
showTicks = FALSE
),
timelineOpts = timelineOptions(pointToLayer = htmlwidgets::JS(
"
function(data, latlng) {
return L.polygon(latlng, {
color: 'black',
fillColor: 'lightblue',
fillOpacity: 0.5
}).bindTooltip(
'Country: ' + data.properties.Country + '<br/>' +
'Start: ' + data.properties.start + '<br/>' +
'End: ' + data.properties.end,
{permanent: false}
).openTooltip()
}
"
),styleOptions = styleOptions(
radius = 3,
color = 'red',
stroke = F,
fill = TRUE,
fillColor = NULL,
fillOpacity = NULL),
))
The above code only generates the map but not popping labels.