Filter selected data on shiny with leaflet

Viewed 43

I would like to make an interactive map in shiny, and filter as follows: first, select the name_region column, and then only the selected region will appear on the map. I would also like to have a way to optionally mark the state or municipality polygon. If nothing is checked, I would like all polygons to appear on the map.

Could someone help me with these first steps please?


library(shiny)
library(leaflet)
library(shinyWidgets)
library(sf)
library(geobr)

#Read states
SP <- read_state("SP",2019)
RJ <- read_state("RJ",2019)
PI <- read_state("PI",2019)
BA <- read_state("BA",2019)

#Read municipalities
SP_M <- read_municipality("SP",2019)
RJ_M <- read_municipality("RJ",2019)
PI_M <- read_municipality("PI",2019)
BA_M <- read_municipality("BA",2019)

#Rbind
States_all <- rbind(SP,RJ,PI,BA)
Mun_all <- rbind(SP_M,RJ_M,PI_M,BA_M)

#Transform coordinates
States_all <- st_transform(States_all, crs = 4326)
Mun_all <- st_transform(Mun_all, crs = 4326)

#UI
ui <- fluidPage(
  leafletOutput("mymap"),
  
  fluidPage(
    selectInput("name_region", "Region", choices = unique(States_all$name_region))
  ))

#SERVER
server <- function(input, output, session) {
  

  output$mymap <- renderLeaflet({
    leaflet() %>% 
      addScaleBar() %>%
      addTiles() %>%
      addPolygons(data=Mun_all,color = "blue", fillColor = "transparent",weight = 1,
                  smoothFactor = 0.5,opacity = 1.0,popup = ~as.character(name_muni)) %>%
      addPolygons(data=States_all,color = "black",
                  fillColor = "transparent",weight = 1,smoothFactor = 0.5, opacity = 1.0,
                  popup = ~as.character(name_state))

  })
  
  observe({
    leafletProxy("mymap") %>%
      clearShapes()
  })
  
}

#SHINYAPP
shinyApp(ui, server)

0 Answers
Related