R Language Introduction to Geographical Maps Dynamic Leaflet maps in Shiny applications


Example

The Leaflet package is designed to integerate with Shiny

In the ui you call leafletOutput() and in the server you call 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)

However, reactive inputs that affect the renderLeaflet expression will cause the entire map to be redrawn each time the reactive element is updated.

Therefore, to modify a map that's already running you should use the leafletProxy() function.

Normally you use leaflet to create the static aspects of the map, and leafletProxy to manage the dynamic elements, for example:

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)

enter image description here