使用leafletProxy,observeEvent和shiny / leaflet应用程序时出现问题

时间:2017-11-24 03:23:28

标签: r shiny leaflet

在过去的几个小时里,我一直在玩我的编码,使用if语句,observeEvent和leafletProxy的形式,但我似乎无法让它工作。生命表是预期寿命数据。它是三列,县,男,女。我似乎无法使单选按钮工作,而且它始终保持男性。

基本上,我希望我的传单地图根据单选按钮的输入提供不同的布局。无论是男性的预期寿命还是女性,以及获得弹出窗口。

library(shiny)
library(leaflet)
library(tigris)
library(dplyr)

lnd <- counties(state = 'IN', cb = TRUE, resolution = '20m')

#Read life table
life <- read.table("life.txt",sep="\t", header=TRUE)

lnd@data <- left_join(lnd@data, life, by = c('NAME' = 'county'))

popup <- paste0("County name: ", lnd$NAME, "<br>", "Life Expectancy: ", round(lnd$male,2))
popup2 <- paste0("County name: ", lnd$NAME, "<br>", "Life Expectancy: ", round(lnd$female,2))


ui <- shinyUI(fluidPage(#theme = "bootstrap.css",

titlePanel("Life Exptectancy in Indiana Counties: "),
h3("A Spatial Analysis Project"),
br(),
sidebarLayout(position = "right",

            sidebarPanel(
              tags$b("Life Expectancy in Indiana, U.S.A."),
              hr(),
              radioButtons("gender",     "Gender:",c("Male"="Male","Female"="Female")),

              hr()
            ),
            mainPanel(
              leafletOutput("map")
            )
   )
))

server <- function(input, output) {
  output$map <- renderLeaflet({
    leaflet(lnd) %>%
      addPolygons() %>%
      addProviderTiles(providers$CartoDB.Positron)
  })
  observeEvent (input$gender == "Male", {
    leafletProxy("map", data=lnd) %>%
      clearShapes() %>%
      addPolygons(stroke = FALSE, smoothFactor = 0.2, fillOpacity = 1, popup = popup)
  })
  observeEvent (input$gender == "Female", {
    leafletProxy("map", data=lnd) %>%
      clearShapes() %>%
      addPolygons(stroke = FALSE, smoothFactor = 0.2, fillOpacity = 1, popup = popup2)
  })
}
shinyApp(ui, server)

这是我的应用The app remains blue, and keeps the same male data no matter if I click female or male. I know it has to do with something with leafletProxy but cant figure it out

的照片

1 个答案:

答案 0 :(得分:0)

您需要为用户输入创建一个反应式数据集。您在代码中使用了相同的数据集 lnd

我不知道您的数据是如何构建的,而且由于我没有您的数据,我希望在此示例中能够理解。

# Data filtered male
lndMale <- reactive({
      lnd[lnd$gender == input$gender, ]
})  


# Data filtered female
lndFemale <- reactive({
      lnd[lnd$gender == input$gender, ]
})  

然后在需要的地方使用反应式数据集。

server <- function(input, output) {
  output$map <- renderLeaflet({
    leaflet(lnd) %>%
      addPolygons() %>%
      addProviderTiles(providers$CartoDB.Positron)
  })
  observeEvent (input$gender == "Male", {
    leafletProxy("map", data=lndMale()) %>%
      clearShapes() %>%
      addPolygons(stroke = FALSE, smoothFactor = 0.2, fillOpacity = 1, popup = popup)
  })
  observeEvent (input$gender == "Female", {
    leafletProxy("map", data=lndFemale()) %>%
      clearShapes() %>%
      addPolygons(stroke = FALSE, smoothFactor = 0.2, fillOpacity = 1, popup = popup2)
  })
}

也许您必须更改部分代码,并在某处使用 isolate,我没有数据集。