单击传单/闪亮中的组时如何添加多边形

时间:2016-11-16 20:33:17

标签: r shiny leaflet

有一个示例显示如何使用overlayGroup控制在使用传单时要隐藏或显示在地图上的图层。但是,即使我们将图层设置为隐藏,仍然需要加载和添加shapefile。我有一个非常大的shapefile,所以我希望只在我点击该组时添加它。例如,请考虑以下示例

library(shiny)

ui <- fluidPage(leafletOutput("map"))

server <- function(input, output) {

outline <- quakes[chull(quakes$long, quakes$lat),]

output$map <- renderLeaflet({
leaflet(quakes) %>%
# Base groups
addTiles(group = "OSM (default)") %>%
addProviderTiles("Stamen.Toner", group = "Toner") %>%
addProviderTiles("Stamen.TonerLite", group = "Toner Lite") %>%

# Overlay groups
addCircles(~long, ~lat, ~10^mag/5, stroke = F, group = "Quakes") %>%
addPolygons(data = outline, lng = ~long, lat = ~lat,
            fill = F, weight = 2, color = "#FFFFCC", group = "Outline") %>%
hideGroup("Outline") %>%
hideGroup("Quakes") %>%
# Layers control
addLayersControl(
  baseGroups = c("OSM (default)", "Toner", "Toner Lite"),
  overlayGroups = c("Quakes", "Outline"),
  options = layersControlOptions(collapsed = FALSE))
 })
}

shinyApp(ui = ui, server = server)

运行时,它会将所有图层添加到“地图”中,然后将其隐藏到我的理解中。我想知道如何将addPolygons移到此外部,并在我点击layercontrol中的“Outline”时使其成为一个反应。

1 个答案:

答案 0 :(得分:1)

你可以这样做:

ui <- fluidPage( checkboxInput('outline', "Outline"), leafletOutput("map"))

server <- function(input, output) {

  outline <- quakes[chull(quakes$long, quakes$lat),]

  output$map <- renderLeaflet({
    leafletplot <- leaflet(quakes) %>%
      # Base groups
      addTiles(group = "OSM (default)") %>%
      addProviderTiles("Stamen.Toner", group = "Toner") %>%
      addProviderTiles("Stamen.TonerLite", group = "Toner Lite") %>%
      addCircles(~long, ~lat, ~10^mag/5, stroke = F, group = "Quakes")


  if(input$outline)
      leafletplot <- leafletplot %>% addPolygons(data = outline, lng = ~long, lat = ~lat,
                  fill = F, weight = 2, color = "#FFFFCC", group = "Outline")

    leafletplot %>%   hideGroup("Quakes") %>%
      # Layers control
      addLayersControl(
        baseGroups = c("OSM (default)", "Toner", "Toner Lite"),
        overlayGroups = c("Quakes"),
        options = layersControlOptions(collapsed = FALSE))
  })
}

shinyApp(ui = ui, server = server)