rr-sfr-leaflet

Adjusting bounds in Leaflet with sf column


I'm making a little app in Shiny that holds data for countries and regions, and where users will be able to choose a region. Then the idea is that the leaflet map that I have in the app will zoom in and focus on the chosen region (i.e. user clicks "Europe" and the map zooms in on Europe).

I can't figure out how I should go about using the simple featuresgeometry column as the filter for the leaflet map. Here's a simply example (not in Shiny, but the problem is not Shiny-related, I imagine).

library(rnaturalearth) 
library(dplyr)
library(leaflet)

# sf data:
earth <- ne_countries(returnclass = "sf") %>% 
  select(Region = region_un, geometry)

# little dataset:
df <- data_frame(
  Region = c("Europe", "Africa", "Asia", "Oceania", "Americas"),
  Score = c(0.85, 0.77, 0.81, 0.93, 0.79)
)
# join:
df <- full_join(df, earth)

# simulate what I'm doing in Shiny:
input <- list()
input$region <- "Europe"

df2 <- filter(df, Region == input$region)

leaflet(df2) %>% addTiles()

This produces: enter image description here

Which is the same as if I had used df (the unfiltered dataframe). Any ideas on how I could go about this? I couldn't find it in the Shiny/leaflet docs.


Solution

  • We could use sf::st_coordinates to extract the values from df2$geometry, get the average latitude and longitude then use leaflet::setView() to focus on our region of interest:

    library(sf)
    coords <- st_coordinates(df2$geometry)
    lng <- mean(coords[,1])
    lat <- mean(coords[,2])
    
    leaflet(df2) %>% addTiles() %>%
        setView(lng, lat, zoom = 3) # 3 for "continent" level
    

    enter image description here

    There are some special methods for updating leaflet maps in a Shiny setting mainly leafletProxy(), those are described pretty well in the docs.