rgoogle-mapsggmaprgooglemaps

How to display google map directions given latitude and longitude information in r


I have with me the latitude and logitude information for few locations. Here is a sample:

lat<-c(17.48693,17.49222,17.51965,17.49359,17.49284,17.47077)
long<-c(78.38945,78.39643,78.37835,78.40079,78.40686,78.35874)

I want to plot these locations in some order(say lat-long combination of first elements in the above vectors will be the starting point and i need to travel in the same order till last location) with google map directions in R. Upon some search I found that there is a google map api from which i can get google map screenshot of specified locations and on top of it we need to plot lines to connect them. But what I need is google map driving directions to connect the locations (not ggplot lines). Please help.


Solution

  • This basically comes down to creating a route_df and then plotting the results as geom_path. For example, for a single route, you could do something like this:

    library(ggmap)
    
    route_df <- route(from = "Hyderabad, Telangana 500085, India",
                      to = "Kukatpally, Hyderabad, Telangana 500072, India",
                      structure = "route")
    
    my_map <- get_map("Hyderabad, Telangana 500085, India", zoom = 13)
    
    ggmap(my_map) +
      geom_path(aes(x = lon, y = lat), color = "red", size = 1.5,
                data = route_df, lineend = "round")
    

    Map with route

    So you could probably approach this by generating each of the from-to routes and rbind-ing all of the results into one large route_df and plotting the final results. It's easier for others to help you if you make an attempt and show where (with code) you are getting stuck. You may want to edit your original question or possibly submit a new one after you show what you have tried.

    This SO post with this answer should prove helpful.