My shiny app features a leaflet map that I would like to manipulate using custom JavaScript through the shinyjs
package. See below for a basic example:
app.R
# 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.
};
The main challenge here is accessing the map object once it has been created. While the example focuses on adding a marker, the ultimate goal is to interact with an API and display additional data on the map based on user actions.