Reputation: 255
I want to make a map using leaflet in shiny with a checkboxGroupInput inside the map and use the inputs of the checkboxGroupInput to update the data that is used to make the map. But I don't know how to use those inputs, I tried the code below but it didn't work.
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 %>% filter(cat %in% input$x))%>%
addTiles() %>%
addMarkers(~long,~lat) %>%
addControl(checkboxGroupInput(inputId = 'x',
'Select cat',
unique(df$cat)))
})
}
shinyApp(ui, server)
Upvotes: 2
Views: 948
Reputation: 5677
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)
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)
Upvotes: 2