Change Leaflet Map Dynamically based on Multiple Reactive expressions

风流意气都作罢 提交于 2019-12-25 01:34:59

问题


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.


回答1:


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
         )


来源:https://stackoverflow.com/questions/53070730/change-leaflet-map-dynamically-based-on-multiple-reactive-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!