Search code examples
rshinyshinydashboardreactiver-leaflet

Change Leaflet Map Dynamically based on Multiple Reactive expressions


In the example Data Frame DF, I have the following columns.

gender <- c("Male", "Female","Female", "Male")
Location <- c("AB", "BC", "CD", "DE")
hasTV <- c("Yes","Yes","No","No")
Latitude <- c(49.82380908513249,59.478568831926395,59.478568831926395,49.82380908513249)
Longitude <- c(-10.8544921875,-10.8544921875,2.021484375,2.021484375)
DF <- data.frame(gender,Location,hasTV,Latitude,Longitude)

Under UI, i've used radiobuttons to select options from hasTV, checkboxGroupInput to select Gender and selectInput to create a dropdown of Location. I've implemented this in fluidRow as shown below.

sex <- unique(DF$gender)
loc <- unique(DF$Location)
hastv <- unique(DF$hasTV)

radioButtons("radio_hastv",label = "Has TV", choices = hastv, selected = "Yes")
checkboxGroupInput("checkbox_gender", label = "Gender", choices = sex, selected = sex)
selectInput("Location", label = "Location", choices=loc, selected = "AB")
leafletOutput("mymap", height = 415)

In the server function, I have multiple reactive expressions based on the input selected. This is how I've implemented the expressions.

 filtered_gender <- reactive({
   DF[DF$gender == input$checkbox_gender,]
 })

 filtered_hastv <- reactive({
   DF[DF$hasTV == input$radio_hastv,]
 })

 filtered_loc <- reactive({
   DF[DF$Location == input$loc,]
 })

I've already rendered the leaflet map. However, I'd like my map to change whenever all these three inputs are somehow selected. e.g. if a person selects, gender=Male, location = DE and hasTV=No, the appropriate map with the correct gps is plotted on the map.

So far, i'm only able to update leaflet map using one reactive expression as shown below.

 observe(leafletProxy("mymap", data = filtered_loc()) %>%
           clearMarkers()%>%
           addMarkers(radius =3)%>%
           label = ~htmlEscape(DF$hasTV)
         )  

How do I go about incorporating the other reactive expressions so that the map changes accordingly. Thanks.


Solution

  • You need to move all those filters in one reactive and use that in your leaflet plot -

    library(dplyr)
    
    filtered_data <- reactive({
       DF %>%
         filter(gender %in% input$checkbox_gender,
                hasTV %in% input$radio_hastv,
                Location %in% input$loc
                )
     })
    
     observe(leafletProxy("mymap", data = filtered_data()) %>%
               clearMarkers()%>%
               addMarkers(radius =3)%>%
               label = ~htmlEscape(hasTV) # note change; using DF here is wrong
             )