Search code examples
rshinydashboardshapefileshiny-reactivityr-leaflet

R Shiny Leaflet Selector for shapefile to be displayed


New to R shiny, new to shapefiles, new to coding anything outside of data cleansing/analysis.

I want to display where particular services are available in my state on a map. I have shapefiles for postcodes (zipcodes) for my state. I have a csv file for 14 different types of government services available for zipcodes.

The shape of the CSV is to have a new line for each service available (i.e. if 3 services are available in that suburb, there will be 3 lines all having the same postcode).

From the CSV, I have split out 14 dataframes, one for each service type. I have made an inner join for each of these to the postcode shapefile. I have 14 data frames that have spatial polygons only for suburbs that have the service available.

I have made popup labels for the suburbs using code type:

serviceA$label <- with(serviceA, paste (serviceA$town_name, serviceA$more_info))

I did this separately for each of the 14 service types (serviceB, serviceC and so on) which doesn't seem elegant but it functions.

Now, here's where I can't work out what to do. How do I use a selector to choose the service I'm interested in and only display that map?

I've found examples for selectively adding markers etc, but I can't work out how to use the selector to choose each dataframe containing only the shapefiles of interest. Please let me know if I have I set this up incorrectly from the start.

What I've tried is:

ui <- fluidPage(selectInput(inputId = "Selector", label ="Type of Support", choices = c(
    'Service A', .....), leafletOutput("mymap"))

server <- function(input, output) {
  
  output$mymap <- renderLeaflet({
    **leaflet(input$Selector)** %>% 
      
      addPolygons(popup = ~label, weight = 1)})
}  

shinyApp(ui, server)

I can make the map display properly (but not according to an actual input choice) if I replace the bold part leflet(input$Selector) with leaflet(serviceA), so I assume that part of my code is wrong but I can't find the right syntax or whether you just can't put the outcome of a selector in this place (completely new to everything outside of analysing scientific data, so I may have misunderstood what the ui and server parts can do?).

Thank you for any suggestions :-)


Solution

  • You need to create a reactive expression to be able to retrieve the dataset chosen with input$Selector. Using, get you search for an object with a given name, the one provided by input$Selector in this case.

    server <- function(input, output) {
    
              df <- reactive({ 
                     get(input$Selector) 
                    }) 
    
             output$mymap <- renderLeaflet({
                    # df its updated everytime input$Selector changes
                    leaflet(df()) %>% 
                    addPolygons(popup = ~label, weight = 1)
                    })
    }