I don't know if this could help or not...
# libraries ---------------------------------------------------------------
library(shiny)
library(sf)
library(tidyverse)
library(leaflet)
library(spData)
# data --------------------------------------------------------------------
# data from the package
world <- st_read(system.file("shapes/world.gpkg", package="spData"))
continents <- world %>%
group_by(continent) %>%
summarise()
countries <- world %>%
select(country = name_long)
# modules -----------------------------------------------------------------
map_ui <- function(id) {
ns <- NS(id)
tagList(
leafletOutput(ns("map")),
verbatimTextOutput(ns("click_info"))
)
}
map_server <- function(id, dropdown){
moduleServer(id, function(input, output, session){
output$map <- renderLeaflet({
# initial map
world_map <- leaflet() %>%
addPolygons(data = continents,
group = "base",
fillOpacity = 0.1,
weight = 1,
stroke = TRUE,
color = "black",
opacity = 1) %>%
addPolygons(data = countries,
group = "base",
fillOpacity = 0.1,
weight = 1,
stroke = TRUE,
color = "grey",
opacity = 1)
# add clickabe continents
apply(continents, 1, FUN = function(x) {
world_map <<- addPolygons(world_map,
group = "continents",
layerId = x[[1]],
data = x[[2]],
fillOpacity = 0.1,
weight = 1,
stroke = TRUE,
color = "black",
opacity = 1)
})
# add clickabe countries
apply(countries, 1, FUN = function(x) {
world_map <<- addPolygons(world_map,
group = "countries",
layerId = x[[1]],
data = x[[2]],
fillOpacity = 0.1,
weight = 1,
stroke = TRUE,
color = "grey",
opacity = 1)
})
world_map
})
output$click_info <- renderPrint({
str(input$map_shape_click)
})
# update polygon for new map
observe({
if(length(input$map_shape_click) == 0) return(NULL)
d = switch(dropdown(), "continents" = continents, "countries" = countries)
leafletProxy("map") %>%
showGroup(dropdown()) %>%
hideGroup(setdiff(c("continents", "countries"), dropdown())) %>%
removeShape(layerId = "selection") %>%
addPolygons(data = d[[2]][d[[1]] == input$map_shape_click$id],
layerId = "selection",
fillColor = "darkorange",
fillOpacity = 0.5,
weight = 1,
stroke = TRUE,
color = "blue",
opacity = 1)
})
})
}
# app ---------------------------------------------------------------------
# Define UI for application that draws a histogram
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("type",
label = "Geography type",
selected = "countries",
choices = c("countries", "continents"))
),
mainPanel(
map_ui("map")
)
)
)
server <- function(input, output, session) {
drop_val <- reactive(input$type)
# map from server
map_server("map", dropdown = drop_val)
}
shinyApp(ui, server)