Search code examples
rshinyr-leafletchoropleth

How do I integrate multiple choropleth maps made with Leaflet in Shiny?


I have created three separate choropleth maps in Leaflet, all are across Europe with the same countries being used. Each choropleth map shows a different type of ratio and has two layers for 1999 and 2009.

Whilst I have successfully integrated the choropleth maps individually to Shiny with the year layers, I want to be able to just have one Shiny map with a drop down bar to click between the three different choropleth maps, whilst still keeping my layers for each map.

Can anyone suggest how to do this?


Solution

  • You can use a leafletProxy for that. I slightly modified the example from here to better suit what you are asking for. Hope this helps!

    library(shiny)
    library(leaflet)
    
    ui <- bootstrapPage(
      tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
      leafletOutput("map", width = "100%", height = "100%"),
      absolutePanel(top = 10, right = 10,
                    selectInput("maptype", "Map type: ",
                                choices = c("map 1", "map 2", "map 3")
                    )
      )
    )
    
    server <- function(input, output, session) {
    
      # Reactive expression for the data subsetted to what the user selected
      filteredData <- reactive({
        if(input$maptype=="map 1") return(quakes[sample(1:nrow(quakes),50,replace=TRUE),])
        if(input$maptype=="map 2") return(head(quakes,50))
        if(input$maptype=="map 3") return(tail(quakes,50))
    
      })
    
    
      output$map <- renderLeaflet({
        leaflet(quakes) %>% addTiles() %>%
          fitBounds(~min(long), ~min(lat), ~max(long), ~max(lat))
      })
    
      observe({
        leafletProxy("map", data = filteredData()) %>%
          clearShapes() %>%
          addCircles(radius = ~10^mag/10, weight = 1, color = "#777777", fillOpacity = 0.7, popup = ~paste(mag)
          )
      })
    
    
    }
    
    shinyApp(ui, server)