0

Suppose I have the following shapefile:

library(sf)  
library(leaflet)
library(leafgl)
library(colourvalues)
library(leaflet.extras)


nc <- st_read(system.file("gpkg/nc.gpkg", package="sf"), quiet = TRUE) %>% 
  st_transform(st_crs(4326)) %>% 
  st_cast('POLYGON')

# code for plot/visualization - works
leaflet(data = nc) %>% addPolygons( stroke = FALSE) %>% addTiles(group = "OSM") %>%  addProviderTiles(provider = providers$OpenStreetMap) %>% addPolygons(data = nc, weight=1, popup = ~NAME,
                label = ~NAME, group = "name", col = 'blue') %>% 
    addSearchFeatures(targetGroups  = 'name', options = searchFeaturesOptions(zoom=10, openPopup=TRUE))

enter image description here

My Question: Within leaflet, is it possible to only load a "part" of this map?

For example, suppose I only want to load the USA - is it possible to do this?

I know that there are ways around this - for example, I could try and configure the zoom to a specific long/lat and then "lock" the map.... but is there a way to only load a select part of the map within leaflet?

1
  • 1
    /../load a "part" of this map/../ - part of the shapefile / sf object or part of the basemap?
    – margusl
    Commented Jul 14, 2023 at 9:42

1 Answer 1

0

I am not fully certain that I read your "load" part correctly; I assume you are asking about how to interactively plot only a subset of a larger shapefile.

Assuming this reading is correct: you can leverage the fact that sf objects are modified data.frames - and use one of the filtering methods that data frames support. My personal preference is dplyr::filter() but base R subsetting will get you to equivalent result.

Consider this piece of code; what it does is:

  • removes non-essential parts of your leaflet call (for the sake of clarity & brevity)
  • in the data argument of your addPolygons call uses a filtered version of the nc shapefile, with only County Ashe shown out of the 100 NC counties in total
library(sf)  
library(leaflet)

nc <- st_read(system.file("gpkg/nc.gpkg", package="sf"), quiet = TRUE) %>% 
  st_transform(st_crs(4326)) %>% 
  st_cast('POLYGON')

# code for plot/visualization - works
leaflet() %>% 
  addProviderTiles(provider = providers$OpenStreetMap) %>% 
  addPolygons(data = dplyr::filter(nc, NAME == "Ashe"), 
              weight=1, 
              popup = ~NAME, 
              label = ~NAME, 
              group = "name", 
              col = 'blue')

[a map showing 1 out of 100 NC counties1

Not the answer you're looking for? Browse other questions tagged or ask your own question.