如何在传单 addPolylines 中绘制 MULTILINESTRING?

How to plot MULTILINESTRING in leaflet addPolylines?

leaflet documentation 说:

Line and polygon data can come from a variety of sources: [...] MULTIPOLYGON, POLYGON, MULTILINESTRING, and LINESTRING objects (from the sf package)

但是如何在传单中使用这些对象?

这是一个 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 循环来分别绘制这些线之外,还有其他解决方案吗?

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

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