Skip to content

Instantly share code, notes, and snippets.

@rCarto
Created December 17, 2020 11:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rCarto/ce6f65386bbe919774d513c180df7ef0 to your computer and use it in GitHub Desktop.
Save rCarto/ce6f65386bbe919774d513c180df7ef0 to your computer and use it in GitHub Desktop.
library(sf)
library(osrm)
library(maptiles)
# build a bbox for Paris
bb <- st_bbox(c(xmin = 643069, ymin = 6857478,
xmax = 661079, ymax = 6867081),
crs = 2154)
# get map tiles
osm <- get_tiles(x = bb, provider = "CartoDB.PositronNoLabels",
crop = TRUE, zoom = 13)
# define origine & destination points
pts <- st_as_sf(data.frame(x = c(648883, 654708),
y = c(6859631, 6864869)),
coords = c("x","y"), crs = 2154)
# get route by car
car <- osrmRoute(src = pts[1,], dst = pts[2,], returnclass = "sf",
osrm.profile = "car", overview = "full")
Sys.sleep(1)
# get route by bike
bike <- osrmRoute(src = pts[1,], dst = pts[2,], returnclass = "sf",
osrm.profile = "bike", overview = "full")
Sys.sleep(1)
# get route by foot
foot <- osrmRoute(src = pts[1,], dst = pts[2,], returnclass = "sf",
osrm.profile = "foot", overview = "full")
# build figure
png("osrm.png", width = 1511, height = 842)
par(mar = c(0,0,0,0))
plot_tiles(osm)
plot(st_geometry(car), add = T, col = "navy", lwd = 5)
plot(st_geometry(bike), add = T, col = "tomato", lwd = 4)
plot(st_geometry(foot), add = T, col = "darkgreen", lwd = 1.5)
plot(st_geometry(pts), cex = 2, pch = c(21), add = T, bg = "goldenrod")
cr <- paste0(
"T. Giraud, 2020 - osrm 3.4.0\n",
"Map: © OpenStreetMap contributors © CARTO\n",
"Routing: OSRM - https://routing.openstreetmap.de/\n",
"Data: © OpenStreetMap contributors, ODbL 1.0 - ",
"http://www.openstreetmap.org/copyright"
)
mtext(text = cr, side = 1, adj = 0, line = -1 )
legend(x = 652828,
y = 6862128,
legend =
c(paste0("car (", round(car$duration,0), "min)"),
paste0("bike (", round(bike$duration,0), "min)"),
paste0("foot (", round(foot$duration,0), "min)")),
col=c("navy", "tomato", "darkgreen"),
lty=c(1,1,1), cex=2,
box.lty=0, lwd = c(5,4,1.5))
dev.off()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment