Create raster tiles using R tiler package for leaflet dashboard

106 views Asked by At

For a dashboard, I'm trying to create a leaflet map with raster tiles for faster rendering of the map. I'm using the R package 'tiler' for creating the tiles. The original data is polygon, which I'm trying to rasterize, and then convert to tiles. There are several of these tiles, each with multiple zoom levels. Reproducible code below fails.

---
title: "try"
date: "`r Sys.Date()`"
output:
  flexdashboard::flex_dashboard:
  orientation: rows 
  vertical_layout: fill
runtime: shiny
---
  
```{r setup, include = FALSE}
knitr::opts_chunk$set(echo=FALSE)
library(flexdashboard)
library(shiny)
library(tidyverse)
library(sf)
library(leaflet)
library(stars)
library(tiler)

pdf(NULL)


nc <- st_read(system.file("shape/nc.shp", package="sf")) %>% st_transform(4326)
subset <- nc %>% filter(SID74 <=5)
    
  # map
  splitField <- "SID79"
years <-  unique(subset[[splitField]])
subset$SID74 <- as.character(subset$SID74)

for (i in 1:length(years)) {
  tmp <- subset[subset[[splitField]] == years[i], ]
  assign(paste0("year", i), tmp)
}
```

Map
===========================================================
  
Row
-----------------------------------------------------------
### Map

```{r}

 colour6 <- tibble(
    numbers = c("0", "1", "2", "3", "4","5"),
    Color = c('#FFFF33',  '#00CC99', '#006633' , '#99CC99', 
           '#6699CC','#CC9900'))
  
  m1 <- leaflet() %>% 
    setView(lng = -79.5, lat = 36,zoom =7) %>% 
    addTiles(group = "OSM (default)")
  
  for (i in 1:length(years)) {
      dat <- get(paste0("year",i))
       dat_col <- merge( x =dat, y =colour6, by.x ="SID74", by.y="numbers")
       
       ras <- st_rasterize(dat_col[,"numbers"], dx= 100, dy = 100)
       ras4326 <- st_warp(ras, crs = st_crs(4326))
       
       # create subfolders in existing path
       dir.create(file.path("./", i), showWarnings = FALSE)
       
        tile_dir <- file.path(paste0("./",i))
        tiles <- tile(ras4326, tile_dir, "0-3", col = colour6$Color)

        m1 <- m1 %>% addTiles(tiles,
                   group = paste0(i),
                   options = tileOptions(opacity = 0.8))
  }

  m1 <- m1 %>%   addLayersControl(
      baseGroups = c("OSM"),
      options = layersControlOptions(collapsed = FALSE),
      overlayGroups  =  unique(years))  %>%
    addLegend(colors = colour6$Color, labels = colour6$numbers)

renderLeaflet({ 
  m1
})

```

Expected output will be like figure below except that instead of polygon it would be tiles. Output with polygon

0

There are 0 answers