问题
How would I receive data, created in a .js
file in the server.R
in shiny?
I am using the leaflat library and I need the extend the LatLngBounds of the current map view has. I need this variable in the server.R
for furhter processing.
So i have
mycode.js
//get bounds of extend of view
$(document).ready(function() {
var myBounds = map.getBounds();
Shiny.onInputChange("bounds", myBounds);
});
which I include in the ui.R
like
tags$body(tags$script(src="mycode.js"))
Thats how my Server.R
looks like:
myBoundsR <- reactive(
as.numeric(input$bounds)
print(input$bounds)
)
However, how would I receive the data in the server.R
file, coming from my mycode.js
?
It feels like Shiny.addCustomMessageHandler
is only to receive data in .js
(or .R
) while session$sendCustomMessage
can only be used in the .R
files? What would I use to send something from a .js
file to the server.R
file?!
Or can I simply use the variable bound
as if I created it in the server.R
file?!
回答1:
If you want to get the map bounds, you can use input$map_bounds
, if map is the id of your leaflet map.
Here is an example, (using the leaflet example code from the tutorial)
library(shiny)
library(leaflet)
r_colors <- rgb(t(col2rgb(colors()) / 255))
names(r_colors) <- colors()
ui <- fluidPage(
leafletOutput("map")
)
)
server <- function(input, output, session) {
points <- cbind(rnorm(40) * 2 + 13, rnorm(40) + 48)
observe({
print(input$map_bounds)
})
output$map <- renderLeaflet({
leaflet() %>% addTiles()
})
}
shinyApp(ui, server)
回答2:
Regarding what NicE wrote:
In the file.js
var myVariable = //do something
Shiny.onInputChange("variableNameToWriteInServer.R", myVariable)
In the server.R
observe({
# thats how you access the variable
input$myVariable
#do something with the variable. To see if it worked something like
})
That should do the trick. If you use the getBounds()
function keep that in mind Leaflet : Firing an event when bounds change. Also, you might not receive any output since the getBounds()
function does not return the bounds of the window when the window extend is not changed. But, its only execute once. In the article I linked is a solution for this.
For further undocumented communication in Shiny (server.R and ui.R) read here: https://ryouready.wordpress.com/2013/11/20/sending-data-from-client-to-server-and-back-using-shiny/
来源:https://stackoverflow.com/questions/32141128/receiving-data-from-js-in-server-r-shiny