我如何在闪亮的 R 应用程序中使用传单添加控制输入?

How can i use the leaflet add control inputs in the shiny R app?

我想使用带有 checkboxGroupInput 的 shiny 传单制作地图,并使用 checkboxGroupInput 的输入来更新用于制作地图的数据。 但我不知道如何使用这些输入,我尝试了下面的代码,但没有用。 我会很感激任何建议。

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)
  

我觉得使用层控件使用addLayersControl更简单。您只需要使用数据框的列 cat 设置 addMarkersgroup 参数。最后,将 addLayersControl 的参数 overlayGroups 设置为 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)

每组使用不同的图标

R Leaflet documentation 一样,有许多可能的方法来获得自定义图标。以下是您的代码之一。请注意,您需要为所有可能的类别提供一个图标。

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)