rr-leaflet

Force initial zoom to truncate portion of the data


I'm working on generating several thousand static images out of leaflet maps. I would like the images to be zoomed in, so that a portion of the data layer is truncated, so that the plotted data extend to the edge of the map and "beyond" (similar to coord_cartesian in ggplot).

I can get the view I want by plotting the example below, then manually zooming in and getting a screenshot, but I need to automate this for my full workflow. Using minZoom and setView hasn't resolved this, and fitBounds seems to remove the partially truncated raster.

library(sf)
library(leaflet)
library(raster)
set.seed(1)
df <- expand.grid(X = seq(706832, 707832, 100), 
                  Y = seq(4344683, 4345683, 100)) 
df$Temp <- rnorm(nrow(df), 10, 3)

df_sf <- st_as_sf(x = df, coords = c("X", "Y"), 
                  crs = "+proj=utm +zone=11") |>
  st_transform(crs = "+proj=longlat +datum=WGS84")

r <- raster(extent(df_sf),
            nrows = sqrt(nrow(df_sf)), ncols = sqrt(nrow(df_sf)),  
            crs = "+proj=longlat +datum=WGS84", vals=df_sf$Temp)

leaflet(options = leafletOptions(
            # the zoom level doesn't seem to affect the displayed map 
            attributionControl=FALSE, minZoom = 10)) %>% 
        addTiles() %>% 
        addRasterImage(r, opacity = 0.6) 
        # this line results in an empty base map
        # fitBounds(lng1 = -114.5, lat1 = 39.23, 
        #           lng2 = -114.5, lat2 = 39.28)  

Solution

  • library(sf)
    library(leaflet)
    library(raster)
    
    set.seed(1)
    df <- expand.grid(X = seq(706832, 707832, 100), 
                      Y = seq(4344683, 4345683, 100)) 
    df$Temp <- rnorm(nrow(df), 10, 3)
    
    df_sf <- st_as_sf(x = df, coords = c("X", "Y"), crs = "+proj=utm +zone=11") |>
      st_transform(crs = "+proj=longlat +datum=WGS84")
    
    r <- raster(extent(df_sf),
                nrows = sqrt(nrow(df_sf)), ncols = sqrt(nrow(df_sf)),  
                crs = "+proj=longlat +datum=WGS84", vals=df_sf$Temp)
    
    data_bounds <- st_bbox(df_sf)
    center_lng <- mean(c(data_bounds[1], data_bounds[3]))
    center_lat <- mean(c(data_bounds[2], data_bounds[4]))
    
    leaflet(options = leafletOptions(attributionControl = FALSE,
                                     zoomSnap = 0.25,
                                     zoomDelta = 0.25)) %>% 
      addScaleBar(position = "bottomright",
                  options = scaleBarOptions(imperial = FALSE)) %>% 
      addTiles() %>% 
      addRasterImage(r, opacity = 0.6) -> m
    
    m %>% setView(lng = center_lng, lat = center_lat, zoom = 17.00)
    

    m %>% setView(lng = center_lng, lat = center_lat, zoom = 17.25)
    

    m %>% setView(lng = center_lng, lat = center_lat, zoom = 17.50)
    

    Created on 2025-07-09 with reprex v2.1.1