在 server.R 闪亮中从 .js 接收数据

Receiving data from .js in server.R shiny

我如何接收在 shiny 的 server.R 中的 .js 文件中创建的数据?

我正在使用 leaflat 库,我需要扩展当前地图视图的 LatLngBounds。我需要 server.R 中的这个变量进行进一步处理。

所以我有

 mycode.js

//get bounds of extend of view
$(document).ready(function() { 

var myBounds = map.getBounds();
Shiny.onInputChange("bounds", myBounds);



});

我在 ui.R 中加入了

tags$body(tags$script(src="mycode.js"))

这就是我的 Server.R 的样子:

  myBoundsR <- reactive(
  as.numeric(input$bounds)
  print(input$bounds)
  )

但是,我如何接收来自我的 mycode.jsserver.R 文件中的数据?

感觉Shiny.addCustomMessageHandler只能在.js(或.R)中接收数据,而session$sendCustomMessage只能在.R文件中使用?我将使用什么将内容从 .js 文件发送到 server.R 文件?!

或者我可以简单地使用变量 bound 就像我在 server.R 文件中创建它一样吗?!

如果你想获取地图边界,你可以使用input$map_bounds,如果map是你的leaflet地图的id。

这是一个示例,(使用 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)

关于 NicE 写的内容:

file.js

var myVariable = //do something
Shiny.onInputChange("variableNameToWriteInServer.R", myVariable)

server.R

observe({
# thats how you access the variable
    input$myVariable
#do something with the variable. To see if it worked something like
})

这应该可以解决问题。如果您使用 getBounds() 函数,请记住 Leaflet : Firing an event when bounds change。此外,您可能不会收到任何输出,因为当 window 扩展未更改时,getBounds() 函数不会 return window 的边界。但是,它只执行一次。在我链接的文章中有一个解决方案。

有关 Shiny(server.R 和 ui.R)中进一步未记录的通信,请阅读此处:https://ryouready.wordpress.com/2013/11/20/sending-data-from-client-to-server-and-back-using-shiny/