Shiny 应用程序中的动态 Leaflet 映射
该单张软件包旨在与闪亮 integerate
在 **ui 中,**你可以调用 leafletOutput()
,在服务器中调用 renderLeaflet()
library(shiny)
library(leaflet)
ui <- fluidPage(
leafletOutput("my_leaf")
)
server <- function(input, output, session){
output$my_leaf <- renderLeaflet({
leaflet() %>%
addProviderTiles('Hydda.Full') %>%
setView(lat = -37.8, lng = 144.8, zoom = 10)
})
}
shinyApp(ui, server)
但是,影响 renderLeaflet
表达式的反应性输入将导致每次更新反应元素时重绘整个地图。
因此,要修改已经运行的地图,你应该使用 leafletProxy()
函数。
通常,你使用 leaflet
来创建地图的静态方面,并使用 leafletProxy
来管理动态元素,例如:
library(shiny)
library(leaflet)
ui <- fluidPage(
sliderInput(inputId = "slider",
label = "values",
min = 0,
max = 100,
value = 0,
step = 1),
leafletOutput("my_leaf")
)
server <- function(input, output, session){
set.seed(123456)
df <- data.frame(latitude = sample(seq(-38.5, -37.5, by = 0.01), 100),
longitude = sample(seq(144.0, 145.0, by = 0.01), 100),
value = seq(1,100))
## create static element
output$my_leaf <- renderLeaflet({
leaflet() %>%
addProviderTiles('Hydda.Full') %>%
setView(lat = -37.8, lng = 144.8, zoom = 8)
})
## filter data
df_filtered <- reactive({
df[df$value >= input$slider, ]
})
## respond to the filtered data
observe({
leafletProxy(mapId = "my_leaf", data = df_filtered()) %>%
clearMarkers() %>% ## clear previous markers
addMarkers()
})
}
shinyApp(ui, server)