16.3 Click leaflet map
Some info about using leaflet with shiny. https://rstudio.github.io/leaflet/shiny.html
Example of clicking on a leaflet map and getting coordinates
Code
library(shiny)
library(leaflet)
library(tidyverse)
# Define UI
ui <- fluidPage(
titlePanel("Example"),
mainPanel(leafletOutput("map"))
)
# Define server logic, and account for User interaction
server <- function(input, output, session) {
output$map <- renderLeaflet({
mymap <- leaflet() %>%
addTiles() %>%
setView(lng = -73.95,
lat = 40.73,
zoom = 12)
mymap
})
# when map is clicked, get the coordinates and show marker on the map
observeEvent(input$map_click, {
click <- input$map_click
## print coords to the console
print(click)
## display the click on the map
proxy <- leafletProxy("map")
proxy %>%
clearGroup("new_point") %>% ## remove the previous point
addCircles(click$lng,
click$lat,
radius = 100,
color = "red",
group = "new_point")
})
}
shinyApp(ui = ui, server = server)