rr-leaflet

Why is a map not displayed when I call leaflet in a function


I want to customize some plot-functions using leaflet. My problem is, that the maps are not displayed in the html as soon as I use leaflet inside a function. Does anybod know a solution?

Here is an example and what I have tried:

Save this as .Rmd
```{r, c1, echo = FALSE}
map <- function() {
  library(leaflet)
  m <- leaflet(width = "100%") %>%
    addTiles(group = "OSM") %>%
    addProviderTiles("Stamen.TonerLite") %>%
    addLayersControl(
      baseGroups = c("OSM", "Stamen.TonerLite"))
  return(m)
}

map_poa <- function() {
  m <- map()
  m %>% addCircleMarkers(lat = c(47, 47.5),
                         lng = c(8, 8.5),
                         stroke = FALSE,
                         radius = 10,
                         fillOpacity = 0.8,
                         clusterOptions = markerClusterOptions())
    print(m)
  return(m)
}
```

One of those plot should work somehow. What I tried:

Add this chunk to the above .Rmd
```{r, c2, echo = FALSE}
# map() # Works
map_poa() # map without content
# print(map_poa()) # Does not work at all (Nothing shown)
# plot(map_poa()) # Does not work (Throws error)
```

Without a function, everything gets displayed:

Add this chunk to the above .Rmd
```{r, c3, echo = FALSE}
m <- map()
m %>% addCircleMarkers(lat = c(47, 47.5),
                       lng = c(8, 8.5),
                       stroke = FALSE,
                       radius = 10,
                       fillOpacity = 0.8,
                       clusterOptions = markerClusterOptions())
print(m)
```

Solution

  • You need to assign the addCircleMarkers call to your map m in map_poa()

    map_poa <- function() {
      m <- map()
      # m <- m %>% addCircleMarkers( # also ok
      m <- addCircleMarkers(map = m,
                            lat = c(47, 47.5),
                            lng = c(8, 8.5),
                            stroke = FALSE,
                            radius = 10,
                            fillOpacity = 0.8,
                            clusterOptions = markerClusterOptions())
    
      return(m)
    }
    

    Then the markers will be shown when calling map_poa()