我有一个带有现有传单地图的闪亮应用程序。我希望能够在渲染后通过shinyjs
包使用自定义javascript来操纵此地图。下面是一个最小的示例:
应用程序
# packages ----------------------------------------------------------------
library(dplyr)
library(leaflet)
library(shiny)
library(shinyjs)
# ui ----------------------------------------------------------------------
ui <- fluidPage(
useShinyjs(),
extendShinyjs(script = "my_js.js"),
leafletOutput(outputId = "map", height = "80vh"),
tags$hr(),
tags$p("Button to run the JS code"),
actionButton(inputId = "go", label = "Add a Marker")
)
# server ------------------------------------------------------------------
server <- function(input, output, session){
# define a simple map
output$map <- renderLeaflet({
leaflet() %>%
addProviderTiles("CartoDB.Positron")
})
# observe the go button and run the shinyjs.addMarker function
observeEvent(
eventExpr = input$go,
handlerExpr = js$addMarker()
)
}
# run ---------------------------------------------------------------------
shinyApp(ui = ui, server = server)
my_js.js
shinyjs.addMarker = function(){
// get the map - this bit doesn't work!
var map = document.getElementById('map');
// create a marker and add to map
var marker = new L.marker([53, -1]).addTo(map);
// really I'd be going off and querying an API, or doing
// something else for which there is no handy R function.
};
问题实际上是在创建地图对象后如何访问它。显然,在此示例中,我只是添加了一个标记,可以使用
leafletProxy()
进行操作,但实际上,我想查询API,并在用户执行操作时将额外的数据带到地图上。任何其他方式的帮助或建议,将不胜感激!
克里斯
最佳答案
您可以使用htmlwidtget
的onRender()
函数到达地图对象。然后,您可以将其保存到全局范围的变量中(通过在创建变量时跳过var
关键字)。它在JavaScript代码中的任何位置都可用。
output$map <- renderLeaflet({
leaflet() %>%
addProviderTiles("CartoDB.Positron") %>%
htmlwidgets::onRender("
function(el,x) {
map = this;
}
")
})
然后,您的my_js.js如下所示:
shinyjs.addMarker = function(){
// create a marker and add to map
var marker = new L.marker([53, -1]).addTo(map);
// really I'd be going off and querying an API, or doing
// something else for which there is no handy R function.
};
关于javascript - 使用ShinyJS使用javascript处理 Shiny 应用中的现有Leaflet map ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50049420/