I run into a problem when working with multiple tabs.
When I run the dashboard and switch to tab2
, the polygon for the predefined selected radio button (Northampton) does not appear by itself. I need to press one of the buttons first for one of the polygons to appear.
So how can I get the Northampton polygon to appear immediately when I switch to tab2
?
I have attached a minimalist example code below.
I think I misunderstood something with the reactive part, but I need some help to solve this.
library(shinydashboard)
library(shiny)
library(leaflet)
library(sf)
library(dplyr)
# load shapefiles
cities <- st_read(system.file("shape/nc.shp", package="sf"))
#### Dashboard ####
header <- dashboardHeader(
title = "example"
)
# Sidebar
sidebar <- dashboardSidebar(
sidebarMenu(
menuItem("Tab 1", tabName = "tab1", icon = icon("circle-info")),
menuItem("Tab 2", tabName = "tab2", icon = icon("euro-sign"))))
# Body
body <- dashboardBody(
tabItems(
tabItem(tabName = "tab1",
h2("homescreen")
),
tabItem(tabName = "tab2",
fluidRow(
box(
title = "Map",
leafletOutput("map")
),
box(
title = "Choices",
radioButtons("select_city", "Select the city:",
c("Northampton" = "1832",
"Hertford" = "1833"))
)
)
)
)
)
# ui
ui <- dashboardPage(header, sidebar, body)
# Server
server <- function(input, output, session) {
# basemap
output$map <- renderLeaflet({
leaflet(options = leafletOptions(zoomControl = TRUE, zoomSnap = 0.5, zoomDelta = 1, wheelPxPerZoomLevel = 75)) %>%
addProviderTiles(providers$Esri.WorldTopoMap) %>%
setView(-77.27, 36.42, zoom = 9) %>%
addScaleBar(position = "topright")
})
# determine shapefile
reactivePolygon <- reactive({
if (input$select_city == 1832) {
cities[5,]
}
else {
cities[6,]
}
})
# load shapefile to map
observe({
leafletProxy("map") %>%
clearShapes() %>%
addPolygons(data = st_transform(reactivePolygon(), 4326))
})
}
# Funktion
shinyApp(ui, server)