I think it is simpler to use a layer control using addLayersControl. You only need to set the group parameter of addMarkers with the column cat of your data frame. Finally, set the parameter overlayGroups of addLayersControl with the unique values of column cat.
library(shiny)
library(leaflet)
df <- data.frame(
cat = sample(letters[1:3],10, replace = TRUE),
long = runif(10,60,100),
lat = runif(10,40,60)
)
ui <- fluidPage(
leafletOutput("map1")
)
server <- function(input, output, session) {
output$map1 <- renderLeaflet({
leaflet(df)%>%
addTiles() %>%
addMarkers(~long, ~lat, group = ~cat) %>%
addLayersControl(
overlayGroups = unique(df$cat),
options = layersControlOptions(collapsed = FALSE)
)
})
}
shinyApp(ui, server)
Using different icons per group
As is in R Leaflet documentation, there are many possible ways to have custom icons. Below is one of them for your code. Please note that you need to provide an icon for all possible categories.
library(shiny)
library(leaflet)
df <- data.frame(
cat = sample(letters[1:3],10, replace = TRUE),
long = runif(10,60,100),
lat = runif(10,40,60)
)
leafIcons <- icons(
iconUrl = sapply(df$cat, function(x) switch (x,
"a" = "https://leafletjs.com/examples/custom-icons/leaf-green.png",
"b" = "https://leafletjs.com/examples/custom-icons/leaf-red.png",
"c" = "https://leafletjs.com/examples/custom-icons/leaf-orange.png"
)),
iconWidth = 38, iconHeight = 95,
iconAnchorX = 22, iconAnchorY = 94,
shadowUrl = "https://leafletjs.com/examples/custom-icons/leaf-shadow.png",
shadowWidth = 50, shadowHeight = 64,
shadowAnchorX = 4, shadowAnchorY = 62
)
ui <- fluidPage(
leafletOutput("map1")
)
server <- function(input, output, session) {
output$map1 <- renderLeaflet({
leaflet(df)%>%
addTiles() %>%
addMarkers(~long, ~lat, group = ~cat, icon = leafIcons) %>%
addLayersControl(
overlayGroups = unique(df$cat),
options = layersControlOptions(collapsed = FALSE)
)
})
}
shinyApp(ui, server)