Search code examples
htmlrknitrr-leaflet

Leaflet Layer Tiles not switchable when .html (= .Rmd output) is opened with browser


For several days now, the basic layer tiles "OSM" and "Stamen.TonerLite" (which I've been using for over a year as standard tiles for my maps) are not shown correctly – i.e. it's not possible anymore to switch between them.

As long as the map is shown in RStudio and RStudio Viewer, everything works perfectly. However, as soon as I open the corresponding .html-file of the .Rmd-output in a Browser (I tried chrome, internet explorer, edge and firefox), it's not possible anymore to switch between the tiles. Either "OSM" is shown and I can't switch to "Stamen.TonerLite" or vice versa.
I've tried different layer tiles or more than 2 layer tiles, but with the same result. There's always only one layer tile visible even when I switch to others.

Reproducible example for my case:

---
title: "stackoverflow"
author: " "
date: " "
output: html_document
---

```{r, echo = T}
library(leaflet)

m <- leaflet() %>%
     addTiles(group = "OSM") %>%
     addProviderTiles("Stamen.TonerLite") %>%
     addLayersControl(baseGroups = c("OSM", "Stamen.TonerLite")) %>%
     addCircleMarkers(lat = 47.4,
                      lng = 9.37,
                      radius = 10,
                      fillOpacity = 1.0)
m
```

enter image description here

enter image description here


Solution

  • Try this, the point is to pipe in the two provider tiles to addTiles() argument

    ---
    title: "stackoverflow"
    author: " "
    date: " "
    output: html_document
    ---
    
    ```{r, echo = T}
    library(leaflet)
    
    m <- leaflet() %>%
     addTiles() %>%
     addProviderTiles(providers$OpenStreetMap, group = "OSM") %>%
     addProviderTiles(providers$Stamen.TonerLite, group = "Toner Lite") %>%
     addLayersControl(baseGroups = c("OSM", "Toner Lite")) %>%
     addCircleMarkers(lat = 47.4,
                      lng = 9.37,
                      radius = 10,
                      fillOpacity = 1.0)
    m
    ```