rshinyr-leaflet

Adding text title on top of leaflet within Shiny


I'm looking to add a little text blurb inside a leaflet map within Shiny. This answer works great for leaflet outside of Shiny, but I can't seem to find a solution to doing this within Shiny.

Toy example:

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

ui <- fluidPage(
        selectInput("Year", "Choose a sampling year", choices = 2016:2021, selected = 2016),
        leafletOutput("map"))

server <- function(input, output, session){
  
  output$map <- renderLeaflet({
    leaflet() %>%
      addTiles() 
  })
  
  observe({
    title <- paste("Chosen year:", input$Year)    
                            
    ## add title as text in corner of leaflet using leaflet proxy
    
    })
  }

shinyApp(ui = ui, server = server)

Solution

  • addControl() works fine in Shiny, but I presume you are referring to the fact that old ones don't get removed when the year is changed? The solution is to add a layerID and use removeControl() first:

    library(dplyr)
    library(shiny)
    library(leaflet)
    
    ui <- fluidPage(
            selectInput("Year", "Choose a sampling year", choices = 2016:2021, selected = 2016),
            leafletOutput("map"))
    
    server <- function(input, output, session){
    
      output$map <- renderLeaflet({
        leaflet() %>%
          addTiles()
      })
    
      map <- leafletProxy("map")
    
      observe({
        title <- paste("Chosen year:", input$Year)
        map %>%
          removeControl("title") %>%
          addControl(title, position = "topright", layerId = "title")
      })
    
      observeEvent(input$add_markers, {
          lat <- runif(1, -90, 90)
          lng <- runif(1, -180, 180)
          map %>%
            addMarkers(lng = lng, lat = lat)
        })
    
    }
    
    shinyApp(ui = ui, server = server)