michaeldorman / mapsapi

'sf'-Compatible Interface to Google Maps APIs
Other
50 stars 14 forks source link

Multiple origins using mapsapi (mp_get_routes, and mp_get_segments) #18

Closed JosephSanchezB closed 2 years ago

JosephSanchezB commented 2 years ago

Dear Michael,

I would like to compute routes and segments from multiple origins with a common endpoint. I tried the code below, but I get the message "Error in mp_get_routes (Directions_ways): Google Maps API status NOT FOUND".

Could you give me some advice please?

Directions_ways <- mp_directions( origin = c("-0.249791993+-78.52884114", "-0.20205+-78.49327", "-0.204889258+-78.50143433", "-0.204889258+-78.50143433", "-0.204889258+-78.50143433", "-0.204889258+-78.50143433"), destination = c("-0.209296982091499+-78.4914229738011"), alternatives = TRUE, departure_time = Sys.time(), traffic_mode = "pessimistic", key = key, quiet = TRUE ) r <- mp_get_routes(Directions_ways)

michaeldorman commented 2 years ago

You can't pass multiple origins at once to mp_directions. However, you can execute the function separately for each origin, and collect the results into a list:

origins = c("-0.249791993+-78.52884114", "-0.20205+-78.49327", "-0.204889258+-78.50143433", "-0.204889258+-78.50143433", "-0.204889258+-78.50143433", "-0.204889258+-78.50143433")
docs = lapply(origins, function(i) 
    mp_directions(
        origin = i,
        destination = c("-0.209296982091499+-78.4914229738011"),
        alternatives = TRUE,
        departure_time = Sys.time(),
        traffic_mode = "pessimistic",
        key = key,
        quiet = TRUE
    )
)

Then, you can get the list of routes (or segments) from each result as follows:

routes = lapply(docs, mp_get_routes)
routes[[1]]  ## route from 1st origin
routes[[2]]  ## route from 2nd origin
# etc.