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)

StackOverflow 文件