我正在使用ggmap构建一个包含多个路径点的路线,但路线功能似乎不能处理路径点。我只能使用单个来自/来。
为了解决这个问题,我想到了逐腿创建路线,并为每条腿调用route()和geom_leg()。由于代码重复,这并不理想。
我想知道是否可以实现这一点。
作为一个例子。
我在下面创建了示例代码。什么是减少重复的理想方法?
start<-c("CH1 6JS","CH1 1RS","CH1 2HT")
dest<-c("CH1 1RS","CH1 2HT","CH1 3DX")
leg <-function(start, dest)
return (route(from=start,to=dest,mode = c("walking"),structure = c("legs")))
l<-leg(start[1], dest[1])
base<-qmap('Chester, UK', zoom = 15, maptype = 'road',
base_layer = ggplot(aes(x = startLon, y = startLat), data = l))
b<-geom_leg(aes(x = startLon, y = startLat, xend = endLon, yend = endLat),
alpha = 2/4, size = 2, data = l, colour = 'red')
l<-leg(start[2], dest[2])
c<-geom_leg(aes(x = startLon, y = startLat, xend = endLon, yend = endLat),
alpha = 2/4, size = 2, data = l, colour = 'red')
l<-leg(start[3], dest[3])
d<-geom_leg(aes(x = startLon, y = startLat, xend = endLon, yend = endLat),
alpha = 2/4, size = 2, data = l, colour = 'red')
base+b+c+d
答案 0 :(得分:0)
我最终使用了一个循环。
start<-c("CH1 6JS","CH1 1RS","CH1 2HT")
dest<-c("CH1 1RS","CH1 2HT","CH1 3DX")
df<-data.frame(start,dest)
leg <-function(start, dest){
r<- route(from=start,to=dest,mode = c("walking"),structure = c("legs"))
c<- geom_leg(aes(x = startLon, y = startLat, xend = endLon, yend = endLat),
alpha = 2/4, size = 2, data = r, colour = 'blue')
return (c)
}
a<-qmap('Chester, UK', zoom = 15, maptype = 'road')
for (n in 1:3){
#l<-leg(start[n], dest[n])
l<-leg(as.character(df[n,1]), as.character(df[n,2]))
a<-a+l
}
a