使用具有反应性值的 leafletProxy 函数时,R leaflet 不会渲染地图

问题描述 投票:0回答:1

我正在尝试创建一个传单地图,当用户更改选择时,该地图将更新而不会重新绘制。

我有一个数据框 testDF,其中包含城镇名称、lat、lng 和 popn 变量。我希望将城镇绘制在地图上,当用户选择城镇时,标记只能由 R 清除,而不应重新绘制。但是当我运行应用程序时,它会运行但地图不会呈现。我无法找出错误所在,我需要有人帮助找出错误。

下面是代码


library(shiny)

testDF \<- data.frame(Towns = c("Arua","Nebbi", "Moyo", "Kampala","Mbarara"),
lat = c(0.0113, 0.134, 0.1543, 0.1891, 0.12321),
lng = c(30.113, 30.551, 30.001, 31.008, 31.190),
popn = c(14000, 10000, 3000, 50000, 30000))

# Define UI

ui \<- fluidPage(

# Application title

titlePanel("Plot town population"),
sidebarLayout(
sidebarPanel(
selectInput(inputId = "towns", label = "select town", choices = testDF$Towns)),

      mainPanel(
        leafletOutput("TestMap",
                      height = "100vh")
        
      )
    )

)


# Define server logic

server \<- function(input, output, session) {
#define reactive variable
filterReact\<- reactive({
filter(testDF, testDF$Towns == !!input$towns)

    })
    
    #plot Map data
    output$TestMap <- renderLeaflet({
      leaflet(filterReact()) %>%
        addTiles() %>%
        addMarkers()
      
      
      mapModifier <-  leafletProxy(mapId = "TestMap", data =filterReact(), session)
      
      observeEvent(input$towns, {
        mapModifier %>%
          clearMarkers() %>%
          addMarkers()
      })
      
    })

}

# Run the application

shinyApp(ui = ui, server = server)
r shiny
1个回答
0
投票

这似乎给了你你想要的。正如我在评论中所建议的,关键是解除你的反应和观察者的束缚。

library(shiny)
library(leaflet)

testDF <- data.frame(Towns = c("Arua","Nebbi", "Moyo", "Kampala","Mbarara"),
                      lat = c(0.0113, 0.134, 0.1543, 0.1891, 0.12321),
                      lng = c(30.113, 30.551, 30.001, 31.008, 31.190),
                      popn = c(14000, 10000, 3000, 50000, 30000))

ui <- fluidPage(
  titlePanel("Plot town population"),
  sidebarLayout(
    sidebarPanel(
      selectInput(
        inputId = "towns", 
        label = "select town", 
        choices = testDF$Towns
      )
    ),
    mainPanel(
      leafletOutput("TestMap", height = "100vh")
    )
  )
)

server <- function(input, output, session) {
  filterReact<- reactive({
    filter(testDF, testDF$Towns == input$towns)
  })

  output$TestMap <- renderLeaflet({
    leaflet(filterReact()) %>%
      addTiles() %>%
      addMarkers()
  })
  
  observeEvent(input$towns, {
    mapModifier <-  leafletProxy(
      mapId = "TestMap", 
      data =filterReact(), 
      session
    )
    mapModifier %>%
      clearMarkers() %>%
      addMarkers()
  })
}

shinyApp(ui = ui, server = server)
© www.soinside.com 2019 - 2024. All rights reserved.