I am writing an R shiny app that uses leaflet. I'd like the user to be able to click on a point and draw a circle around that point with some popups of interest to the user within that circle. Problem is, after it draws the initial circle, if the user clicks anywhere within that circle, it returns the lat, lon of that circle, not of the exact point where the user clicked.
Here's a minimal reproducible example:
ui.R:
library(shiny)
library(leaflet)
u<-fluidPage(
leafletOutput("map"),
absolutePanel(top = 10, right = 10,
verbatimTextOutput("clickInfo")
)
)
server.R:
start.lng <- -71.057083
start.lat <- 42.361156
size = 5 # in miles
do_onclick <-function(click) {
proxy <- leafletProxy("map")
# remove all markers and popups
proxy %>% clearMarkers()
proxy %>% clearShapes()
# add new marker around the center
proxy %>% addMarkers(lng=click$lng,lat = click$lat,popup='Your Starting Point')
# add new circle
proxy %>% addCircles(lng=click$lng, lat=click$lat,radius=(1609.344*size),color='red')
}
shinyServer(
function(input, output, session) {
######## initial map
output$map <- renderLeaflet({
leaflet() %>% setView(lng = start.lng, lat = start.lat, zoom = 11) %>% addProviderTiles(providers$OpenStreetMap) %>% addTiles() %>% addMarkers(lng= start.lng, lat=start.lat, popup='Boston, MA') %>% addCircles(lng=start.lng, lat=start.lat,radius=(1609.344*size),color='red')
})
#### what to do on non-shape click
observeEvent(input$map_click, {
click<-input$map_click
output$clickInfo <- renderPrint(click)
text <-paste("lat ",click$lat," lon ",click$lng)
print(text)
do_onclick(click)
})
# #### what to do on shape click
observeEvent(input$map_shape_click, {
click<-input$map_shape_click
output$clickInfo <- renderPrint(click)
text <-paste("lat ",click$lat," lon ",click$lng)
print(text)
do_onclick(click)
})
})
Here's the result:
No matter where I click within the red circle I get exactly the same lat, lon (in this example 42.36166, -71.05708).
Does anyone know how to get 'behind' the current shape and get the lat, lon coordinates of the actual point where the user clicked? Note that I tried accessing click$id and click$admin, both were NULL.
Thanks much!