0

I'm building up a route with multiple way points using ggmap but the route function doesn't seem to handle way points. I can only get it working with a single from/to.

To overcome this I thought of creating the route leg by leg, with a call to route() and geom_leg() for each leg. This isn't ideal due to code repetition.

I wonder if it's possible to vectorise this.

As an example.

  1. Plot Base map
  2. For each vector of start/dest call route/geom_leg

I've created sample code below. What's the ideal way to reduce the repetition?

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
Leehbi
  • 789
  • 10
  • 25

1 Answers1

0

I ended up using a loop.

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
Leehbi
  • 789
  • 10
  • 25