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|
@jazzurro's answer is spot-on so that should remain the accepted answer.
As they alluded to, you can do this all within the googleway
package if you want and plot a Google Map. The main difference to using leaflet is that you don't need to decode the polyline, the Google Map can handle the encoded string for you.
polylines <- lapply(1:nrow(mydf), function(x){
foo <- google_directions(origin = unlist(mydf[x, 2:3]),
destination = unlist(mydf[x, 4:5]),
key = apiKey,
mode = "driving",
simplify = TRUE)
## no need to decode the line, just return the string as-is
foo$routes$overview_polyline$points
}
)
df <- data.frame(polylines = unlist(polylines), stringsAsFactors = F)
## add some colour values for the markers
mydf$colour_from <- "red"
mydf$colour_to <- "blue"
## plot the polylines and the markers
google_map(key = mapKey) %>%
add_markers(data = mydf, lat = "from_lat", lon = "from_long", colour = "colour_from") %>%
add_markers(data = mydf, lat = "to_lat", lon = "to_long", colour = "colour_to") %>%
add_polylines(data = df, polyline = "polylines")
Note: I'm the googleway author.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With