kry
kry

Reputation: 11

Add a new marker in map on click event

I am using leaflet library in R Shiny. I want to add a new marker on the map with a mouse click. I am able to fetch latitude and longitude using input$mapid_click option. But I am not able to update the map in shiny app with a new marker.

Upvotes: 1

Views: 1769

Answers (2)

Gordon McDonald
Gordon McDonald

Reputation: 281

Since shiny 1.6.0, observeEvent(event,expression) has been deprecated in favour of observe(expression) %>% bindEvent(event). So the answer above by @Wilmar-van-Ommeren would become:

library(shiny)
library(leaflet)

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

server <- function(input, output, session) {
  output$map <- renderLeaflet({leaflet()%>%addTiles()})

  observe({
    click = input$map_click
    leafletProxy('map')%>%addMarkers(lng = click$lng, lat = click$lat)
  }) %>%
  bindEvent(input$map_click)
}

shinyApp(ui, server)


Upvotes: 0

Wilmar van Ommeren
Wilmar van Ommeren

Reputation: 7699

You can add them using the leafletProxy function.

library(shiny)
library(leaflet)

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

server <- function(input, output, session) {
  output$map <- renderLeaflet({leaflet()%>%addTiles()})

  observeEvent(input$map_click, {
    click = input$map_click
    leafletProxy('map')%>%addMarkers(lng = click$lng, lat = click$lat)
  })
}

shinyApp(ui, server)

Upvotes: 2

Related Questions