使用SF列调整Leaflet(R)中的边界 [英] Adjusting bounds in Leaflet (R) with sf column

查看:173
本文介绍了使用SF列调整Leaflet(R)中的边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Shiny中制作一个小应用程序,其中包含国家和地区的数据,用户可以在其中选择地区.然后的想法是,我在应用程序中拥有的传单地图将放大并专注于所选区域(即用户单击欧洲",地图将放大欧洲).

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

我不知道应该如何使用简单功能geometry列作为传单地图的过滤器.这是一个简单的示例(我想不是在Shiny中,但是问题并不与Shiny相关).

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

这将产生:

与使用df(未过滤的数据帧)相同.关于如何解决这个问题有任何想法吗?我在Shiny/leaflet文档中找不到它.

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.

推荐答案

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

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

有一些特殊的方法可以在主要是leafletProxy()的Shiny设置中更新leaflet映射,这些方法在

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

这篇关于使用SF列调整Leaflet(R)中的边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆