I have an application that reuses several leaflet elements, so I'm trying to build functions to streamline my code.
All of my logical attempts failed, so I utilized an example I was familiar with here. I copied the format and created functions for markers and polygons, seen in the example below:
library(leaflet)
library(shiny)
markerFunction <- function(map, x, y){
addCircleMarkers(
map, x, y,
color = "red"
)
}
polygonFunction <- function(map, polygon){
addPolygons(
map, polygon,
color = "red"
)
}
# shinyapp
shinyApp(
# ui
ui = fixedPage(
# leaflet output
leafletOutput("map", height = 600)
), # END UI
# server
server = function(input, output, session){
# map output
output$map <- renderLeaflet({
leaflet() %>%
addTiles
}) # END RENDER LEAFLET
# map proxy
proxy <- leafletProxy("map")
# observe
observe({
proxy %>%
markerFunction(40, 50) %>%
polygonFunction(gadmCHE)
})
} # END SERVER
)
The marker function works fine, but the polygon function spits the error:
Warning: Error in derivePolygons: addPolygons must be called with both lng and lat, or with neither.
which is the error I get when I don't include data =
explicitly. When I add data = polygon
to the function definition and data = gadmCHE
to the polygonFunction() call, I get the error:
Warning: Error in polygonFunction: unused argument (data = gadmCHE)
Running the markerFunction() on its own yields the expected result, but I'm perplexed how it works without including the map
argument. When I remove it from the function, it no longer works.
I've tried many configurations and can't get any of them to work except for the markerFunction() as it exists in the above example app. I have tried including and excluding the map
argument, explicitly defining other arguments (like x, y, and data) in both the function definition and function calls, excluding the explicit arguments with no luck. I want to create similar functions for polygons as well, but haven't found a solution.
data = polygon
in your polygonFunction. Or you could usemapview::addFeatures
instead which is feature type agnostic so should also work in the markerFunction.data = polygon
to the function and it still didn't work. I tried including it in the function definition but not the function call and vice versa, including it in both, and excluding it from both...no luck!data = polygon
only in the function definition.map
argument! Now to try my more complex example...on that note, do you have any insight why themap
argument is necessary when it's never called in the function?map
argument. Moreover you need to match your functions arguments to those ofaddPolygons
which expects amap
argument at first position.