popup map click is not activate

I've created a basic R Shiny app to extract location data by clicking on a popup map. The functionality works as expected when I first open the popup window. However, after closing the popup by clicking 'close' and reopening it, I encounter an issue where I'm unable to place markers by clicking, and consequently, the coordinates don't update.

library(shiny)
library(leaflet)

ui <- fluidPage(
  headerPanel("Map Marker App"),
  sidebarLayout(
    sidebarPanel(
      actionButton("openMapBtn", "Click to Place Marker")
    ),
    mainPanel(
      verbatimTextOutput("coordinates")
    )
  )
)

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

  marker <- reactiveValues(lat = NULL, lng = NULL)
  

  output$map <- renderLeaflet({
    leaflet() %>%
      addTiles() %>%
      setView(lng = 0, lat = 0, zoom = 2)
  })
  
   observeEvent(input$openMapBtn, {
    showModal(
      modalDialog(
        leafletOutput("popupMap", width = "100%", height = "400px"),
        footer = actionButton("closeBtn", "Close")
      )
    )
  })
  
  output$popupMap <- renderLeaflet({
    leaflet() %>%
      addTiles() %>%
      setView(lng = 0, lat = 0, zoom = 2)
  })
  
  observeEvent(input$popupMap_click, {
    click <- input$popupMap_click
    marker$lat <- click$lat
    marker$lng <- click$lng
    leafletProxy("popupMap") %>%
      clearMarkers() %>%
      addMarkers(lng = click$lng, lat = click$lat)
  })
  
   observeEvent(input$closeBtn, {
    removeModal()
  })
  
   output$coordinates <- renderPrint({
    paste("Latitude:", marker$lat, "Longitude:", marker$lng)
  })
}

shinyApp(ui, server)

Hi @leemengus

according to r - leafletProxy in modalDialog is not updated - Stack Overflow this

output$popupMap <- renderLeaflet({
    req(input$openMapBtn) ### add this and it will work
    leaflet() %>%
      addTiles() %>%
      setView(lng = 0, lat = 0, zoom = 2)
  })

should work.

@vedoa, your code works perfectly. Thank you so much for fixing this issue.

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.