rshinygisr-leaflet

How to make a function for pipe processing of renderLeaflet


I have a question about the processing of render Leaflet in shiny + leaflet. Since the pipe processing (%>%) becomes long, we would like to make the code compact by the function.

One is a file with a reder Leaflet. The other is addAwesomeMarkers used in render Leaflet.

file name:ms_method.R

library(shiny)
library(leaflet)

basepath <- "C:/Users/XXXXX/"
source(paste0(basepath,"ms_method_ex.R"),encoding="utf-8")

ui <- fluidPage(
  
  leafletOutput('maps')
)

server <- function(input, output, session) {

   output$maps <- renderLeaflet({
    
    leaflet()%>%
      addTiles()%>%
      setView(lng=139.8,lat=35.7,zoom=12)%>%
      # addAwesomeMarkers(
      #     lng = c(139.8),
      #     lat = c(35.7),
      #     )
      f1()
    }) 
}
shinyApp(ui, server)

The f1 function is a function defined in an external file. It is read by the source statement.

Next is the function defined in another file.

file name:ms_method_ex.R

f1 <- function(){
  addAwesomeMarkers(
    lng = c(139.8),
    lat = c(35.7),
  )}
  

This will cause an error. What kind of processing should I do? If anyone knows, please let me know. Also, I would be grateful if you could tell me a web page that will be helpful.


Solution

  • The first argument of addAwesomeMarkers is the map. See ?addAwesomeMarkers

    To make your function work, whether in our outside of a pipeline it needs a map argument, i.e. do:

    f1 <- function(map) {
      addAwesomeMarkers(map,
        lng = c(139.8),
        lat = c(35.7),
      )}