如何从leaflet或tmap中裁剪指定区域(以太浩湖为例)
如何在tmap和leaflet中裁剪出太浩湖区域
要从大地图中提取太浩湖区域,关键是先获取太浩湖的地理边界,再基于边界限制地图显示范围。以下是适配你现有代码的具体实现方案:
1. 准备太浩湖边界数据
首先通过osmdata包从OpenStreetMap获取太浩湖的矢量边界(若未安装该包先执行安装命令):
install.packages(c("osmdata", "dplyr")) library(osmdata) library(dplyr) library(sf) # 获取太浩湖的多边形边界 tahoe_bbox <- getbb("Lake Tahoe") tahoe_poly <- opq(bbox = tahoe_bbox) %>% add_osm_feature(key = "natural", value = "water") %>% osmdata_sf() %>% .$osm_polygons %>% filter(name == "Lake Tahoe")
2. 修改tmap代码实现裁剪
基于你现有的tmap代码,添加太浩湖边界并锁定视图范围,就能只显示目标区域:
library(tmap) library(tmaptools) test <- tm_basemap("Esri.DeLorme") + tm_shape(tahoe_poly) + tm_fill("blue", alpha = 0.3) + # 叠加太浩湖区域 tm_view(set.view = st_bbox(tahoe_poly)) # 锁定视图到太浩湖范围 test # 导出裁剪后的地图图片 tmap_save(test, filename = "tahoe_tmap.png", width = 8, height = 6)
3. 修改leaflet代码实现裁剪
针对你提供的leaflet代码,通过fitBounds方法限制地图只能在太浩湖范围内显示:
library(leaflet) # 使用Esri.DeLorme底图的裁剪版本 leaflet(tahoe_poly) %>% addProviderTiles("Esri.DeLorme") %>% addPolygons(fillColor = "blue", fillOpacity = 0.3, color = "black", weight = 2) %>% fitBounds( lng1 = st_bbox(tahoe_poly)[["xmin"]], lat1 = st_bbox(tahoe_poly)[["ymin"]], lng2 = st_bbox(tahoe_poly)[["xmax"]], lat2 = st_bbox(tahoe_poly)[["ymax"]] ) # 或者使用默认底图的裁剪版本 leaflet(tahoe_poly) %>% addTiles() %>% addPolygons(fillColor = "blue", fillOpacity = 0.3, color = "black", weight = 2) %>% fitBounds( lng1 = st_bbox(tahoe_poly)[["xmin"]], lat1 = st_bbox(tahoe_poly)[["ymin"]], lng2 = st_bbox(tahoe_poly)[["xmax"]], lat2 = st_bbox(tahoe_poly)[["ymax"]] )
如果需要导出leaflet的裁剪区域图片,可以用mapview包的mapshot工具:
install.packages("mapview") library(mapview) tahoe_map <- leaflet(tahoe_poly) %>% addProviderTiles("Esri.DeLorme") %>% addPolygons(fillColor = "blue", fillOpacity = 0.3) %>% fitBounds(st_bbox(tahoe_poly)[1], st_bbox(tahoe_poly)[2], st_bbox(tahoe_poly)[3], st_bbox(tahoe_poly)[4]) mapshot(tahoe_map, file = "tahoe_leaflet.png", cliprect = "viewport")
内容的提问来源于stack exchange,提问作者Salvador
相关产品推荐
相关产品推荐

