needRhelp
needRhelp

Reputation: 3148

Add popup to marker added by DrawToolbar

I have a shiny app, where a user can create new points on a leaflet map via the DrawToolbar. Each time a new marker is set, the coordinates are added to a data.frame. I want to show these coordinates as a popup of the newly added markers. Is this possible without loosing the possibility to drag or remove the new markers?

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

ui <- fluidPage(
  leafletOutput("map")
)

data <- data.frame(lat = c(), lon = c())

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

  output$map <- renderLeaflet({
    leaflet() %>% addTiles() %>% 
      addDrawToolbar(
        targetGroup = "new_points",
        polylineOptions = FALSE,
        polygonOptions = FALSE,
        rectangleOptions = FALSE,
        circleOptions = FALSE,
        editOptions = editToolbarOptions(selectedPathOptions = selectedPathOptions()))
  })

  observeEvent(input$map_draw_new_feature, {
    click_lat <- input$map_draw_new_feature$geometry$coordinates[[2]]
    click_lon <- input$map_draw_new_feature$geometry$coordinates[[1]]
    data <- rbind(data, cbind(click_lat, click_lon))
    print(data)
  })

}


shinyApp(ui, server)

Upvotes: 1

Views: 773

Answers (1)

HubertL
HubertL

Reputation: 19544

You can use reactiveValues instead of a global variable to store the new markers, it will replot the map (adding all markers with popup) every time you add one:

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

ui <- fluidPage(
  leafletOutput("map")
)

server <- function(input, output, session) {
  data <- reactiveValues(lat = NULL, lon = NULL)
  output$map <- renderLeaflet({
    # Get setView parameters
    new_zoom <- 2
    if(!is.null(input$map_zoom)) new_zoom <- input$map_zoom
    new_lat <- 0
    if(!is.null(input$map_center$lat)) new_lat <- input$map_center$lat
    new_lon <- 0
    if(!is.null(input$map_center$lng)) new_lon <- input$map_center$lng

    leaflet() %>% addTiles() %>% 
      setView(new_lon,new_lat,zoom = new_zoom) %>% 
      addDrawToolbar(
        targetGroup = "new_points",
        polylineOptions = FALSE,
        polygonOptions = FALSE,
        rectangleOptions = FALSE,
        circleOptions = FALSE,
        editOptions = editToolbarOptions(
          selectedPathOptions = selectedPathOptions()))-> map

    if (!is.null(data$lat)) {
       addMarkers(map, lng=data$lon, lat=data$lat, 
          popup=paste("lat=", data$lat, ", lon=", data$lon))}
    else map
  })

  observeEvent(input$map_draw_new_feature, {
    click_lat <- input$map_draw_new_feature$geometry$coordinates[[2]]
    click_lon <- input$map_draw_new_feature$geometry$coordinates[[1]]
    data$lat <- c(data$lat,click_lat)
    data$lon <- c(data$lon,click_lon)
  })
}

shinyApp(ui, server)

Notice the setView call to avoid zooming to the first marker you add

Upvotes: 1

Related Questions