简体   繁体   中英

How to plot MULTILINESTRING in leaflet addPolylines?

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?

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

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

@mnist, it's even simpler than that. You just need to add the data argument in addPolylines , which allows you to add multiple lines with different data sources:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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