4

I would like to use Shiny Leaflet to render an already existing leaflet map, but problems arise since the initial map is created from an externally hosted (rather complicated) JS file, which I do not have any control over.

I can't seem to get the leaflet map to work with the R Leaflet functions. That is, nothing happens except that the browser console prints: "Couldn't find map with id mapid".

So the question is: How can I make Shiny Leaflet recognise a Leaflet map created on the UI side from an externally hosted JS file, so that it is possible to change the map from the server side.

Below is a minimal example, where a leaflet map is created on the UI side using JS. The app then (unsuccessfully) tries to add new points to the map from the server side.:

library(shiny)
library(leaflet)

ui <- fluidPage(
  # Load leaflet.js
  tags$head(HTML("

                 <link rel='stylesheet' href='https://unpkg.com/leaflet@1.2.0/dist/leaflet.css' integrity='sha512-M2wvCLH6DSRazYeZRIm1JnYyh22purTM+FDB5CsyxtQJYeKq83arPe5wgbNmcFXGqiSH2XR8dT/fJISVA1r/zQ==' crossorigin=''>
                 <script src='https://unpkg.com/leaflet@1.2.0/dist/leaflet.js' integrity='sha512-lInM/apFSqyy1o6s89K4iQUKg6ppXEgsVxT35HbzUupEVRh2Eu9Wdl4tHj7dZO0s1uvplcYGmt3498TtHq+log==' crossorigin=''></script> ")
  ),

  # Setup Map Container
  leafletOutput("mapid", height = "400px"),

  # Setup Base Map
  HTML(
    "
    <script>
    var mymap = L.map('mapid').setView([51.505, -0.09], 13);

    L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
    maxZoom: 18,
    id: 'mapbox.streets'
    }).addTo(mymap);

    L.marker([51.5, -0.09]).addTo(mymap)
    .bindPopup('<b>Hello world!</b><br />I am a popup.').openPopup();
    </script>
    "
  ),

  br(),
  actionButton("recalc", "New points")
)


server <- function(input, output, session) {
  # Create Random Data Point
  points <- eventReactive(input$recalc, {
    cbind(rnorm(40) * 2 + 13, rnorm(40) + 48)
  }, ignoreNULL = FALSE)

  # When recalc is clicked add markers to map
  observeEvent(input$recalc,{
    leafletProxy("mapid", session) %>%
      addMarkers(data = points())
  })
}

shinyApp(ui, server)

Any help will be greatly appreciated!

Cheers

KarlJensen
  • 59
  • 5

0 Answers0