r - 使用 sf 列调整 Leaflet (R) 中的边界

标签 r shiny leaflet sf

我正在用 Shiny 制作一个小应用程序,它保存国家和地区的数据,用户可以在其中选择一个地区。然后我的想法是我在应用程序中拥有的传单 map 将放大并专注于所选区域(即用户单击“欧洲”并且 map 放大到欧洲)。

我不知道应该如何使用简单的 featuresgeometry 列作为传单 map 的过滤器。这是一个简单的例子(不是在 Shiny 中,但我想问题与 Shiny 无关)。

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()

这会产生: enter image description here

这就好像我使用了 df(未过滤的数据帧)一样。关于如何解决这个问题的任何想法?我在 Shiny/leaflet 文档中找不到它。

最佳答案

我们可以使用 sf::st_coordinatesdf2$geometry 中提取值,获取平均纬度和经度然后使用 leaflet::setView() 关注我们感兴趣的区域:

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

有一些特殊的方法可以在 Shiny 设置中更新 leaflet map ,主要是 leafletProxy(),这些在 docs 中有很好的描述。 .

关于r - 使用 sf 列调整 Leaflet (R) 中的边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46352567/

相关文章:

r - 保存 ggplotGrob 生成的 ggplot2 时间序列图 grob

RODBC sqlSave() 和映射列名

r - 如何将 mutate_at 与多个函数一起使用,其中每个函数都有参数?

r - 如何在 Shiny R 中动态更改传单 map 的大小?

r - 如何在 Shiny 的应用程序中显示忙碌指示器?

javascript - 当我尝试在信息控件中显示信息时,传单功能 'onEachFeature' 不起作用

javascript - 从 CircleMarker 扩展的标记 - 如何更改点击区域?

r - 一种从 R 访问谷歌街景的方法?

光栅图像低于基础层,而标记保持高于 : xIndex is ignored

javascript - 如何动态添加图层和更新图层控件: leaflet