I've been looking at the nice added functionality of addDrawToolbar in Leaflet/Shiny, which allows for custom drawing of shapes etc.
But i'm interested in sub-setting spatial data by accessing the geometry of the drawn shape, how is this done? There are some efforts here and here but I can't get them to work at any rate.
I thought perhaps that the clever functionality of plot brush might work with leaflet maps but Joe Cheng suggested last year that it wasn't in place.
So, are there any developments or workarounds on this? or has anyone managed to access the geometry of a drawn rectangle using addDrawToolbar?
You could use the
addDrawToolbar
from theleaflet.extras
package.The docs are sparse but this page has the code for the
Leaflet.draw
shiny bindings. You can look for the lines that haveShiny.onInputChange
and in your the server part of your app, use the correspondinginput$event
to get the data passed to theShiny.onInputChange
.Here's a minimal example, you can draw polygons around cities and the names of the cities in the polygon will be displayed below the map:
Edit: Added support in case the user draws a circle.
drawing on and adapting NicE's answer above (accepted), this is what I did to subset and zonal sum a raster, using a drawn rectangle.
Crucially i had to swap over
drawn_polygon <- Polygon(do.call(rbind,lapply(polygon_coordinates,function(x){**c(x[[2]][1],x[[1]][1]**)})))
todrawn_polygon <- Polygon(do.call(rbind,lapply(polygon_coordinates,function(x){**c(x[[1]][1],x[[2]][1]**)})))
to make the extract work, otherwise the extent was the wrong way around.i included
editOptions = editToolbarOptions(selectedPathOptions = selectedPathOptions())
to allow me to delete the drawn polygon but ideally i want it to auto delete when i draw a new one, which i will build in at some point.