我正在尝试根据用户选择创建几个传单地图。我尝试制作一个可重现的示例。 我有一个有四种形状的 sf(即代表北卡罗来纳州的四个县)。用户可以根据县的选择来选择绘制一到四个地图(通过“checkboxGroupInput”进行)。如果用户选择一个县,我应该绘制一张代表用户选择的县的地图。如果用户选择两个县,应该绘制两张地图,等等
我有几行代码,但无法将用户选择连接到我的地图。您可以在下面找到我尝试做的事情。
library(sf)
library(leaflet)
library(mapview)
library(mapedit)
library(DT)
library(viridis)
library(leafem)
nc <- st_read(system.file("shape/nc.shp", package="sf")) %>% head(3)
ui = fluidPage(
titlePanel("Maps"),
sidebarPanel(
checkboxGroupInput('MapNumber','Select Maps', choices = c("Ashe", "Alleghany", "Surry"), selected = "Ashe"),
conditionalPanel(condition="output.MapNum=='1'",
fluidRow(
column(12,
leafletOutput("Map1a")
)
)
),
conditionalPanel(condition="output.MapNum=='2'",
fluidRow(
column(6,
leafletOutput("Map2a")
),
column(6,
leafletOutput("Map2b")
)
)
),
conditionalPanel(condition="output.MapNum=='3'",
fluidRow(
column(6,
leafletOutput("Map3a")
),
column(6,
leafletOutput("Map3b")
),
column(6,
leafletOutput("Map3c")
)
)
)
)
)
server = function(input, output) {
MapInput1a<-reactive({
req(length(input$MapNumber)==1)
input$MapNumber[1]
})
MapInput2a<-reactive({
req(length(input$MapNumber)==2)
input$MapNumber[1]
})
MapInput2b<-reactive({
req(length(input$MapNumber)==2)
input$MapNumber[2]
})
MapInput3a<-reactive({
req(length(input$MapNumber)==3)
input$MapNumber[1]
})
MapInput3b<-reactive({
req(length(input$MapNumber)==3)
input$MapNumber[2]
})
MapInput3c<-reactive({
req(length(input$MapNumber)==3)
input$MapNumber[3]
})
output$Map1a<-renderLeaflet({leaflet()%>% addTiles(group = "OSM") %>%
addProviderTiles("CartoDB", group = "CartoDB") %>%
addProviderTiles("Esri.WorldImagery", group = "Esri.WorldImagery") %>%
addFeatures("?")})# do not know how to plot the feature correctly, and I do not know how to do for output$Map2a,
# output$Map2b, etc.
}
shinyApp(ui, server)
有趣的问题。我会使用一种相当不同的方法来完成工作。我不会创建那么多条件面板,而是编写一个函数,根据所选县的数量创建列的集合。
library(sf)
library(leaflet)
library(shiny)
nc <- st_read(system.file("shape/nc.shp", package="sf")) %>% head(3)
# This function returns a collection of leaflet plots based on county names
maps_ui <-function(counties, shapefiles) {
n_counties <- length(counties)
colum_with <- 12 / n_counties
maps <- purrr::map(
counties,
~shiny::column(
width = colum_with,
leaflet() %>%
addTiles(group = "OSM") %>%
addProviderTiles("CartoDB", group = "CartoDB") %>%
addProviderTiles("Esri.WorldImagery", group = "Esri.WorldImagery") %>%
addPolygons(data = nc[nc$NAME == .x, ]) %>%
addLegend(
position = 'bottomright',
colors = c("#5663E2", "#F4BC35", "#E45F71"),
labels = c ("1", "2", "3"),
opacity = 0.5, title = .x )
)
)
)
return(maps)
}
# The app
ui = fluidPage(
checkboxGroupInput('counties', 'Select Maps', choices = c("Ashe", "Alleghany", "Surry"), selected = "Ashe"),
fluidRow(uiOutput('maps'))
)
server = function(input, output) {
output$maps <- renderUI({
maps_ui(input$counties, nc)
})
}
shinyApp(ui, server)