繁体   English   中英

如何在plot MULTILINESTRING leaflet addPolylines?

[英]How to plot MULTILINESTRING in leaflet addPolylines?

leaflet 文档说:

线和多边形数据可以来自多种来源:[...] MULTIPOLYGON、POLYGON、MULTILINESTRING 和 LINESTRING 对象(来自 sf 包)

然而,我如何在 leaflet 中使用这些对象?

这是一个 MULTILINESTRING 示例:

# attach packages---------------------------------------------------------------
library(dplyr)
library(sf)
library(leaflet)

# set up data ------------------------------------------------------------------
set.seed(5)
data <-  tibble(X = 1:5 * 2 + runif(5),
                Y = 1:5 - runif(5),
                GROUP = c("A", "A", "B", "B", "B"))
# A tibble: 5 x 3
#       X     Y GROUP
#   <dbl> <dbl> <chr>
# 1  2.27 0.798 A    
# 2  4.49 1.61  A    
# 3  6.32 2.11  B    
# 4  8.56 3.45  B    
# 5 10.3  4.16  B 

# create MULTILINESTRING -------------------------------------------------------
multiline <- data %>% 
  st_as_sf( coords = c("X", "Y")) %>% 
  group_by(GROUP) %>% 
  summarize() %>%
  st_cast("MULTILINESTRING") %>% 
  st_set_crs("+init=epsg:2154") %>% 
  st_transform(crs="+proj=longlat +datum=WGS84")

# plot with leaflet ------------------------------------------------------------
leaflet() %>% 
  addTiles() %>% 
  addPolylines(multiline)
# Error in derivePolygons(data, lng, lat, missing(lng), missing(lat), "addPolylines") : 
# addPolylines must be called with both lng and lat, or with neither.

如果这是不可能的,除了分别调用 for 循环到 plot 这些行之外,还有其他解决方案吗?

好的,这比我想象的要容易得多。 只需将MULTILINESTRING object 放入leaflet()

leaflet(multiline) %>% 
  addTiles() %>% 
  addPolylines()

@mnist,它比那更简单。 您只需要在addPolylines中添加data参数,它允许您添加具有不同数据源的多行:

leaflet() %>%
  addTiles() %>%
  addPolylines(data=multiline, color='blue') %>%
  addPolylines(data=otherlines, color='orange')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM