Hello, I have a question and not an issue _per se_.
I am currently trying to develop an R Shiny application using Leaflet. I would like users to pan/zoom around a map to locate an area of interest and then draw a bounding box around that area. With the bounding box defined, I would like to pass the extent information to downstream code to perform a number of calculations.
As a toy example: imagine drawing a bounding box around an area of interest to capture the extent. This information is then passed downstream and used to query GBIF to count the number of unique species that have been observed within that area.
Is there an easy way to accomplish this? I think drawing a bounding box (e.g. like you can do here https://boundingbox.klokantech.com/) would be best from a UX perspective but appreciate this may not be possible within R Shiny.
I would be happy with any solution, not just drawing a bounding box. Another possibility that came to mind would be for a user to pan and zoom to the area of interest then click an action button which will take the bounding box of everything the frame at that moment. Again, though, I'm not sure whether this is even technically possible.
Any help would be greatly appreciated.
This question should probably be on stackoverflow.
But anyway, I think the leaflet.extras package might be useful for this.
I hope this little app helps. After drawing a rectangle, the bbox is printed to the console.
library(shiny)
library(leaflet)
library(leaflet.extras)
library(sf)
ui <- fluidPage(
leafletOutput("map")
)
server <- function(input, output, session) {
output$map <- renderLeaflet({
m <- leaflet() %>%
addTiles() %>%
addDrawToolbar(polylineOptions = F, circleOptions = F, markerOptions = F,
circleMarkerOptions = F, polygonOptions = F)
})
observeEvent(input$map_draw_new_feature, {
feat <- input$map_draw_new_feature
coords <- unlist(feat$geometry$coordinates)
coords <- matrix(coords, ncol = 2, byrow = T)
poly <- st_sf(st_sfc(st_polygon(list(coords))), crs = 4326)
print(st_bbox(poly))
})
}
shinyApp(ui, server)
Or see this blog post about using mapedit shiny modules for this
https://www.r-spatial.org/r/2017/06/09/mapedit_0-2-0.html#edit-as-shiny-module
@trafficonese @tim-salabim
Thank you both for your help, it's very much appreciated. In hindsight I agree this is probably one for SO - I'll make sure I post there in future (unless I find a bug).
I have posted an extension to the above question here (using @trafficonese's code): https://stackoverflow.com/questions/55829499/pass-observeevent-output-to-action-button
Most helpful comment
Or see this blog post about using mapedit shiny modules for this
https://www.r-spatial.org/r/2017/06/09/mapedit_0-2-0.html#edit-as-shiny-module