I'm trying to develop an app in which the user can click on a raster map and values associated with the latitude and logitude of the click will be extracted from associated raster bricks and produces new graphics based on these. The first step is to display the points that the user clicks on over the rasters. The problem is that when I want to display the points on several different rasters (which in my application would be model output maps) it can be quite time consuming and I'd like to isolate the event of adding the points to the map (render the rasters just once). I believe something like this is possible through the leaflet package (leafletProxy) and indeed it would be wonderful if my maps could pan and zoom together as well. Using the leaflet package I can't figure out how to get the latitude and longitude associated with a click event and with the standard renderPlot I can't figure out how to add the points without re-rendering the rasters each time. Here's an example which will (hopefully) clarify the goal is to make this faster and hopefully incorporate leaflet functionality.
require(raster)
require(shiny)
r <- r2 <- raster(ncol=10000,nrow=10000)
values(r) <- seq(1:ncell(r))
values(r2) <- seq(ncell(r):1)
Server<-shinyServer(function(input, output) {
XYs <- reactiveValues(
Xlocs = NULL,
Ylocs = NULL,
vals= NULL
)
# Handle clicks on the plot
observeEvent(input$plot_click, {
if (is.null(XYs$Xlocs)) {
# We don't have a first click, so this is the first click
XYs$Xlocs <- input$plot_click$x
XYs$Ylocs<- input$plot_click$y
} else {
XYs$Xlocs<-append(XYs$Xlocs,input$plot_click$x)
XYs$Ylocs<-append(XYs$Ylocs,input$plot_click$y)
}
XYdat<-as.data.frame(cbind(X=XYs$Xlocs,Y=XYs$Ylocs))
})
output$map1 <- renderPlot({
#Plot the Map
par(oma=c(0,0,0,0),mar=c(0,0,2,0),xpd=FALSE)
plot(r,maxpixels=60000,xaxt="n",yaxt="n",bty="n")
XYdat<-as.data.frame(cbind(X=XYs$Xlocs,Y=XYs$Ylocs))
if((any(!
is.na(XYdat)))){
points(x=XYdat$X,y=XYdat$Y,pch=21,col="black",bg="white",cex=2.5)
}
})
output$map2 <- renderPlot({
#Plot the Map
par(oma=c(0,0,0,0),mar=c(0,0,2,0),xpd=FALSE)
plot(r2,maxpixels=60000,xaxt="n",yaxt="n",bty="n")
XYdat<-as.data.frame(cbind(X=XYs$Xlocs,Y=XYs$Ylocs))
if((any(!
is.na(XYdat)))){
points(x=XYdat$X,y=XYdat$Y,pch=21,col="black",bg="white",cex=2.5)
}
})
}
)
UI<-shinyUI(fluidPage(
plotOutput("map1", click = "plot_click"),
plotOutput("map2", click = "plot_click")
)
)
shinyApp(server=Server,ui=UI)