rgoogle-mapsmapsleafletgoogleway

How to add routes (polylines) between two markers in leaflet


I wish to add the polyline between these two point. How can I do this?

m <- leaflet() %>%
     addPolylines() %>%
     addTiles() %>%  # Add default OpenStreetMap map tiles
     addMarkers(lng = -87.6266382, lat = 41.8674336,
                popup = "starting") %>%
     addMarkers(lng = -87.64847, lat = 41.9168862,
                popup = "Destination")

m  # Print the map

Example of the data.

| region      | from_lat   | from_long    | to_lat      | to_long    |
|-------------|------------|------------- |-------------|----------- |
| 1           | 41.8674336 | -87.6266382  | 41.887544   | -87.626487 |
| 2           | 41.8674336 | -87.6266382  | 41.9168862  | -87.64847  |
| 3           | 41.8674336 | -87.6266382  | 41.8190937  | -87.6230967|

Solution

  • Here is my attempt. Since you want to draw some routes on a leaflet map, you want to achieve this task via the googleway package. It allows you to extract route data using google_directions() and decode_pl(). Since you have multiple routes, you want to use lapply() and create a data set. Once you have the route data, your job is straightforward; you use the data in addPolylines().

    library(dplyr)
    library(googleway)
    library(leaflet)
    
    mydf <- data.frame(region = 1:3,
                       from_lat = 41.8674336,
                       from_long = -87.6266382,
                       to_lat = c(41.887544, 41.9168862, 41.8190937),
                       to_long = c(-87.626487, -87.64847, -87.6230967))
    
    mykey <- "you need to have your API key here"
    
    lapply(1:nrow(mydf), function(x){
    
        foo <- google_directions(origin = unlist(mydf[x, 2:3]),
                                 destination = unlist(mydf[x, 4:5]),
                                 key = mykey,
                                 mode = "driving",
                                 simplify = TRUE)
    
        pl <- decode_pl(foo$routes$overview_polyline$points)
    
        return(pl)
    
            }
        ) %>%
    bind_rows(.id = "region") -> temp
    
    
    m <- leaflet() %>%
         addProviderTiles("OpenStreetMap.Mapnik") %>%
         addPolylines(data = temp, lng = ~lon, lat = ~lat, group = ~region) %>%
         addMarkers(lng = -87.6266382, lat = 41.8674336,
                    popup = "starting")%>%
         addMarkers(data = mydf, lng = ~to_long, lat = ~to_lat,
                    popup = "Destination")
    

    enter image description here