Search code examples
rshinyleafletgolem

Reference to a leaflet map from a golem module to another


I'm building a Shiny app, using Golem as a framework. Inside my app, I have made a couple modules, all linked by a Leaflet map. However, I can't update the map from another module than the one that creates the map.

I have tried to take into account the recommandation made here, to include the map_id and parent_session into module calls, but the app still just crashes whenever I try to bring any changes to the map (with no error trace).

Here's a stripped-down version of my code, in separate files:

app_server.R:

#' The application server-side
#' 
#' @param input,output,session Internal parameters for {shiny}. 
#'     DO NOT REMOVE.
#' @import shiny
#' @import leaflet
#' @noRd
app_server <- function( input, output, session ) {
  
  
  r <- reactiveValues(
    map=NULL,
    origin=list(lat=NULL, lng=NULL),
    destination=list(lat=NULL, lng=NULL)
  )
  
  mod_basemap_server("basemap_ui_1", r, session)
  mod_itinerary_server("itinerary_ui_1", r, map_id="basemap", parent_session=session)
}

app_ui.R:

#' The application User-Interface
#' 
#' @param request Internal parameter for `{shiny}`. 
#'     DO NOT REMOVE.
#' @import shiny
#' @noRd
app_ui <- function(request) {
  tagList( 
    bootstrapPage(      
      mod_basemap_ui("basemap_ui_1"),
      mod_itinerary_ui("itinerary_ui_1")
      )
    
  )
}

mod_basemap.R:

#' basemap UI Function
#'
#' @description A shiny Module.
#'
#' @param id,input,output,session Internal parameters for {shiny}.
#'
#' @noRd 
#'
#' @importFrom shiny NS tagList 
mod_basemap_ui <- function(id){
  ns <- NS(id)
  tagList(
    # Map background
    leaflet::leafletOutput(ns("basemap"))    
  )
}
    
#' basemap Server Functions
#'
#' @noRd 
mod_basemap_server <- function(id, r, session){
  shiny::moduleServer( id, function(input, output, session){
    ns <- session$ns
    
    output$basemap <- leaflet::renderLeaflet({
      # generate base leaflet
      map = leaflet::leaflet(options = leaflet::leafletOptions(zoomControl = FALSE)) %>%
        leaflet::addTiles(leaflet::providers$OpenStreetMap) %>%
        leaflet::addProviderTiles(leaflet::providers$OpenStreetMap,
                                  group="Open Street Map") %>% 
        leaflet::addProviderTiles(leaflet::providers$OpenTopoMap,
                                  group="Open Topo Map") %>% 
        leaflet::addProviderTiles(leaflet::providers$Esri.WorldImagery,
                                  group="Esri World Imagery") %>% 
        leaflet::fitBounds(2.78, 44.85, 3.41, 44.71) %>%
        leaflet::addLayersControl(
          baseGroups = c("Open Street Map", "Open Topo Map", "Esri World Imagery")
        )
      map
    })
        
    # Clicks on the map
    observeEvent(input$basemap_click, {
      click = input$basemap_click
      # Check whether we're updating origin marker or destination marker
      if(r$orig_dest_switch=="orig"){
        r$origin$lat = click$lat
        r$origin$lng = click$lng
        # Add origin marker on the map (after removing previously added origin)
        leaflet::leafletProxy('basemap')%>%
          leaflet::clearGroup("origin") %>%
          leaflet::addMarkers(lng=r$origin$lng, lat=r$origin$lat,
                     group="origin")
      } else {
        r$destination$lat = click$lat
        r$destination$lng = click$lng
        # Add destination marker on the map (after removing previously added destination)
        leaflet::leafletProxy('basemap')%>%
          leaflet::clearGroup("destination") %>%
          leaflet::addMarkers(lng=r$destination$lng, lat=r$destination$lat,
                              group="destination")
      }
    })
    
  })
}

mod_itinerary.R:

#' itinerary UI Function
#'
#' @description A shiny Module.
#'
#' @param id,input,output,session Internal parameters for {shiny}.
#'
#' @noRd 
#'
#' @importFrom shiny NS tagList 
mod_itinerary_ui <- function(id){
  ns <- NS(id)
  tagList(
    absolutePanel(id="vehicleDetails", bottom=10, left=15, h4('Itinerary'),
                  h6("First select an origin on the map, then select a destination before plotting"),
                  style='background-color:white; opacity:0.8;padding: 0 20px 20px 20px',
                  radioButtons(
                    inputId=ns('orig_dest_switch'),
                    h5("Change origin or destination"),
                    choices = c("Origin" = 'orig', "Destination" = 'dest'),
                    inline = TRUE),
                  actionButton(inputId=ns("confirm_itin"), label="Plot itinerary")
    )
  )
  
}

#' itinerary Server Functions
#'
#' @noRd 
mod_itinerary_server <- function(id, r, map_id, parent_session){
  moduleServer( id, function(input, output, session){
    ns <- session$ns
    
    # Change origin/destination switch
    observeEvent(input$orig_dest_switch, {
      r$orig_dest_switch = input$orig_dest_switch
    })
    
    # Click on confirm button
    observeEvent(input$confirm_itin, {
    # Delete previous itineraries
    leaflet::leafletProxy(mapId = map_id, session = parent_session) %>%
      leaflet::clearGroup('itin')
    # Show itinerary on map
    leaflet::leafletProxy(mapId = map_id, session = parent_session) %>%
      leaflet::addPolylines(lng=c(r$origin$lng, r$destination$lng),
                            lat=c(r$origin$lat, r$destination$lat),
                            group='itin')
        
    })
    
    
  })
}
shinyApp(app_ui, app_server)

Solution

  • I don't know why it crashes for you, I didn't have this problem. Still, the main problem was that in app_server.R, you put map_id="basemap" when you call the module for itinerary.

    In mod_basemap.R, the map is indeed called "basemap", but it is wrapped in ns(), which means that its actual id is "name you give when calling the module-" + "id you give to the input". Here, the actual id for the map is therefore "basemap_ui_1-basemap".

    Now, it's not a good idea to specify this whole id (what if you replace "basemap_ui_1" by something else later?), so what you want is to return the map id when you call mod_basemap.R, so that you can use this id in other modules. So at the end of the server part in mod_basemap.R, you can add:

    return(list(map_id = ns("basemap")))
    

    so that you have:

    mod_basemap_server <- function(id, r, session){
      shiny::moduleServer( id, function(input, output, session){
        ns <- session$ns
        
        # ... Code you already have ...
    
        return(list(map_id = ns("basemap")))
        
      })
    }
    

    In app_server.R, you can now assign the module mod_basemap to an object (that I call basemap), and then use basemap$map_id when you call the module mod_itinerary:

    basemap <- mod_basemap_server("basemap_ui_1", r, session)
    mod_itinerary_server("itinerary_ui_1", r, map_id = basemap$map_id, parent_session = session)
    

    I hope this is clear. You can also check this RStudio article about passing information between modules.

    Last thing, you made a typo in mod_itinerary.R, you wrote r$destination$lng where it should be r$destination$lat.

    With that, clicking on two points on the map and then clicking on "Plot itinerary" should display a line between those two points. If you still have some unexpected crashes, I guess this comes from code in other modules that you may have because this code works fine for me.