问题
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