Search code examples
rshinyr-leaflet

Leaflet input$MAPID_center returning NULL


I am building a map using Shiny and want to capture the latitude and longitude of the centre of the map in the variables 'lt' and 'ln'. I am using the below code, however, when it is run, I get NULL values for both 'lt' and 'ln'.

library(shiny)
library(leaflet)
library(leaflet.extras)

server <- function(input, output, session){

output$map <- renderLeaflet({
    leaflet() %>%
    addProviderTiles(providers$OpenStreetMap) %>%
    setView(lng = 147.842393, lat = -24.000942, zoom = 6) %>% 
    addSearchOSM(options = searchOptions(collapsed = TRUE))
})

observeEvent(input$MAPID_center, {
    lt <- input$MAPID_center$lat
    ln <- input$MAPID_center$lng
})

})


Solution

  • Your MAPID is wrong.

    You've defined your map output as output$map. So map is your ID in this case

    When you want to "observe" this map, you need to observe input$map_... objects

    Here's a working example

    library(shiny)
    library(leaflet)
    library(leaflet.extras)
    
    ui <- fluidPage(
      leaflet::leafletOutput(
        outputId = "map"
      )
    )
    
    server <- function(input, output, session){
      
      output$map <- renderLeaflet({
        leaflet() %>%
          addProviderTiles(providers$OpenStreetMap) %>%
          setView(lng = 147.842393, lat = -24.000942, zoom = 6) %>% 
          addSearchOSM(options = searchOptions(collapsed = TRUE))
      })
      
      observeEvent(input$map_center, {
        lt <- input$map_center$lat
        ln <- input$map_center$lng
        
        print(lt); print(ln)
        
      })
      
    }
    
    shinyApp(ui, server)