addPolylines
Leaflet可以使用该功能添加线条。这样做的问题是它假设每条线路都已连接 - 您将把它们全部连接起来。
解决此问题(AFAIK)的最佳方法是使用循环:
library(leaflet)
map3 = leaflet(data) %>% addTiles()
map3 <- map3 %>% addMarkers(~InitialLong,~InitialLat, popup=~Observation)
for(i in 1:nrow(data)){
map3 <- addPolylines(map3, lat = as.numeric(data[i, c(2, 4)]),
lng = as.numeric(data[i, c(3, 5)]))
}
map3
编辑:还有一种更简单的方法是使用 Kyle Walker 的points_to_line 函数(请参阅最底部的代码粘贴副本)。
首先重塑数据,使起点和终点在同一列中:
library(tidyr)
library(dplyr)
z <- gather(dta, measure, val, -Observation) %>% group_by(Observation) %>%
do(data.frame( lat=c(.[["val"]][.[["measure"]]=="InitialLat"],
.[["val"]][.[["measure"]]=="NewLat"]),
long = c(.[["val"]][.[["measure"]]=="InitialLong"],
.[["val"]][.[["measure"]]=="NewLong"])))
然后打电话points_to_line
z <- as.data.frame(z)
y <- points_to_line(z, "long", "lat", "Observation")
现在绘制:
map3 = leaflet(data) %>% addTiles()
map3 %>% addMarkers(~InitialLong, ~InitialLat, popup = ~Observation) %>%
addPolylines(data = y)
Kyle Walker 的 points_to_line 来源:
library(sp)
library(maptools)
points_to_line <- function(data, long, lat, id_field = NULL, sort_field = NULL) {
# Convert to SpatialPointsDataFrame
coordinates(data) <- c(long, lat)
# If there is a sort field...
if (!is.null(sort_field)) {
if (!is.null(id_field)) {
data <- data[order(data[[id_field]], data[[sort_field]]), ]
} else {
data <- data[order(data[[sort_field]]), ]
}
}
# If there is only one path...
if (is.null(id_field)) {
lines <- SpatialLines(list(Lines(list(Line(data)), "id")))
return(lines)
# Now, if we have multiple lines...
} else if (!is.null(id_field)) {
# Split into a list by ID field
paths <- sp::split(data, data[[id_field]])
sp_lines <- SpatialLines(list(Lines(list(Line(paths[[1]])), "line1")))
# I like for loops, what can I say...
for (p in 2:length(paths)) {
id <- paste0("line", as.character(p))
l <- SpatialLines(list(Lines(list(Line(paths[[p]])), id)))
sp_lines <- spRbind(sp_lines, l)
}
return(sp_lines)
}
}