How to plot MULTILINESTRING in leaflet addPolylines?

梦想的初衷 提交于 2021-02-11 15:53:31

问题


The leaflet documentation says:

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

Yet how do I make use of such objects in leaflet?

Here is a MULTILINESTRING example:

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

If this is not possible, is there a solution besides calling a for loop to plot those lines separately?


回答1:


Okay, this has been a lot easier than I thought it would. Just put the MULTILINESTRING object inside of leaflet():

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


来源:https://stackoverflow.com/questions/61411088/how-to-plot-multilinestring-in-leaflet-addpolylines

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!