I'd like to map 2 different routes on 1 map. This is the code I made as an example:
### Plot 2 routes on 1 map
# libraries
library(ggmap)
library(ggplot2)
# plot map
basicmap <- get_map(location = c(lon = 3, lat = 50),
zoom = 12,
maptype = "roadmap",
source = "google",
color = "color") #completely random location
basicmap <- ggmap(basicmap)
# determine routes
routes <- data.frame(from = c("Rocquigny", "Nurlu"),
to = c("Heudicourt","Longavesnes"),
stringsAsFactors = FALSE)
# calculate routes
calculationroute <- function(startingpoint, stoppoint) {
route(from = startingpoint,
to = stoppoint,
mode = "bicycling",
structure = "route")
}
#this function calculates the route
calculatedroutes <- mapply(calculationroute,
startingpoint = routes$from,
stoppoint = routes$to,
SIMPLIFY = FALSE)
#calculate the 2 routes
# draw routes
drawroute <- function(route) {
geom_path(aes(data = route,
x = lon,
y = lat))
}
#this functions draws the route
extendedmap <- basicmap + lapply(X = calculatedroutes,
FUN = drawroute)
plot(extendedmap)
#draw the routes
So theses are the steps I take:
- Background map is created
- I make a dataframe which contains the starting points and endpoints for 2 routes
- Using ggmap I calculate the segments of these routes.
- I try to draw the routes on top of the background map
Sadly the last step fails and this error occurs:
Don't know how to automatically pick scale for object of type function. Defaulting to continuous
Error in data.frame(x = c(2.89030838012694, 3.11003494262694, 2.89030838012694, :
arguments imply differing number of rows: 4, 0
I did a search and this previous question wanted to do the same thing. The solution he finally chose uses a for loop and I'd rather keep my code consistent by using lapply instead.