library(xml2)
library(mapsapi)
library(sf)
## Linking to GEOS 3.6.2, GDAL 2.2.3, proj.4 4.9.3
library(mapview)
# Google Maps API query
key = readLines("~/key")
url = paste0("https://maps.googleapis.com/maps/api/directions/xml?origin=Boston,MA&destination=Concord,MA&waypoints=Charlestown,MA|Lexington,MA&key=", key)
doc = xml2::read_xml(url)
# Get route coordinates
route =
doc %>%
xml_find_all("/DirectionsResponse/route/overview_polyline/points") %>%
xml_text
# Convert to line
rt = lapply(route, mapsapi:::decode_line)
rt = lapply(rt, st_linestring)
rt = lapply(rt, st_sfc, crs = 4326)
rt = do.call(c, rt)
# Map
mapview(rt)