我正在尝试在纬度/经度点之间的Leaflet
地图上创建线条。以下是输入数据示例:
segment_id latitude1 longitude1 latitude2 longitude2 len
1 1 48.15387 17.07388 48.15396 17.07387 10.98065
2 1 48.15396 17.07387 48.15404 17.07377 11.31327
3 1 48.15404 17.07377 48.15410 17.07364 11.74550
4 1 48.15410 17.07364 48.15412 17.07349 11.48138
5 1 48.15412 17.07349 48.15412 17.07334 11.63625
6 2 48.15424 17.07307 48.15432 17.07299 10.79304
结果应为6行lat1,lng1
- > lat2,lng2
。我很难与addPolylines
合作,它会产生额外的不必要的线条,我不知道为什么。
它应该是这样的,没有额外的线堆叠在一起:D
到目前为止,这是我的代码,但它是垃圾:
drawEdges <- function(x) {
d <- cbind(x$latitude1,x$latitude2)
s <- rep(1:nrow(x), each = 2) + (0:1) * nrow(x)
latitudeOut <- d[s]
e <- cbind(x$longitude1,x$longitude2)
t <- rep(1:nrow(x), each = 2) + (0:1) * nrow(x)
longitudeOut <- e[t]
mymap <<- addPolylines(map = mymap,data = x, lng = ~longitudeOut, lat = ~latitudeOut)
}
if (!is.null(edges)){
segments <- split( edges , f = edges$segment_id )
segments
sapply(segments, drawEdges)
}
感谢您的帮助
答案 0 :(得分:3)
要按顺序连接线条,您需要将数据重新整形为长形式,并按顺序排列点。
要在不使用任何空间对象的情况下执行此操作(例如,来自library(sp)
),您需要使用循环添加行。
library(leaflet)
### --- reshaping the data ----
## keep the order - but because we're going to split the data, only use odd numbers
## and we'll combine the even's on later
df$myOrder <- seq(from = 1, to = ((nrow(df) * 2) - 1), by = 2)
## put the data in long form by splitting into two sets and then rbinding them
## I'm renaming the columns using setNames, as we need to `rbind` them
## together later
df1 <- setNames(df[, c("segment_id","latitude1","longitude1", "myOrder")],
c("segment_id", "lat","lon", "myOrder"))
df2 <- setNames(df[, c("segment_id","latitude2","longitude2", "myOrder")],
c("segment_id", "lat","lon", "myOrder"))
## make df2's order even
df2$myOrder <- (df2$myOrder + 1)
df <- rbind(df1, df2)
## can now sort the dataframe
df <- df[with(df, order(myOrder)), ]
## and de-dupelicate it
df <- unique(df[, c("segment_id", "lat","lon")])
### -----------------------------
## ----- plotting ---------------
map <- leaflet(data = df) %>%
addTiles() %>%
addCircles()
## without using any spatial objects, you add different lines in a loop
for(i in unique(df$segment_id)){
map <- addPolylines(map, data = df[df$segment_id == i,],
lat = ~lat, lng = ~lon, group = ~segment_id)
}
map