Search code examples
rshinyr-leaflet

Using addResourcePath for rendering local leaflet tiles


I would like to add local tiles for leaflet to render them offline in a shiny application. Although there are solutions to this on SO for example here and here , I am still ending up with grey map with no tiles.

My example code:

library(shiny)
library(dplyr)
library(RgoogleMaps)

#downloads tiles for a given regions, saves it to C:/Users/.../mapTiles/OSM
for (zoom in 0:16)
  GetMapTiles(center = c(lat = 52.431635, lon = 13.194773),
              zoom = zoom,
              nTiles = round(c(20,20)/(17-zoom)))
#shiny ui 
ui = fluidPage(leafletOutput("map"))

#create basic map, load tiles from directory and set view to centre of downloaded tiles
server = function(input, output, server){
  addResourcePath(prefix = "OSM", "C:/Users/.../mapTiles")
  output$map = renderLeaflet({
    leaflet() %>% 
      addTiles( urlTemplate = "/OSM/{z}_{x}_{y}.png") %>% 
      setView(52.431635, 13.194773 , zoom = 10) %>%  #set to the location with tiles
      addMarkers(52.431635, 13.194773 )
  }
  )
}

shinyApp(ui, server)

Solution

  • In my case, I create my own tiles via gdal2tiles, which takes your data and automatically creates a {z}/{x}/{y}.png folder structure. Please see this link for a nice tutorial and what i mean about the file structure;

    +---14
    |   +---8185
    |     +---5460.png
    |     +---5461.png
    |     +---etc.png
    |   \---8186
    
    # I use the following server (see how my addTiles has a folder structure)
    server <- function(input, output,session) {
       addResourcePath("mytiles", "C:/.../tiles")
       output$tilemap <- renderLeaflet({
         leaflet() %>%
           setView(lng = -4.4, lat = 52, zoom = 12) %>%
           addTiles(urlTemplate = "mytiles/{z}/{x}/{y}.png")
    
       })
    }
    

    Now, as you are downloading tiles from Google Maps to your hard drive, you'll want a slightly different approach as the files are downloaded in a {z}_{x}_{y}.png format, and not produced into a file structure like gdal creates;

    +---11_1098_671.png etc.

    so you need to adjust your addTiles code to reflect this, using underscores, like the Google filenames;

    server <- function(input, output,session) {
      addResourcePath("mytiles", "C:/.../OSM")
      output$tilemap <- renderLeaflet({
        leaflet() %>%
          setView(lng = 13.194773, lat = 52.431635, zoom = 11) %>%
          addTiles(urlTemplate = "mytiles/{z}_{x}_{y}.png")
    
      })
    
    }
    

    Lastly, my setView arguments are in a different order to yours but i'm not sure whether that makes a difference or not.