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)