Routing using OpenStreetMap, R and Openrouteservice

Support for GIS related operations has improved a lot in recent years in the R universe and there are a lot of libraries for GIS. In this case, I wanted to do routing using OpenStreetMap data and the Openrouteservice.

This R script will:

  • Create start and end points for a route
  • Create the fastest route for walking and car travel using Openrouteservice
  • Create an interactive web map using Leaflet
  • Export the web map to an HTML file

Code:

# Set working directory
setwd("C:\\R\\")


# Install Openrouteservice library
# install.packages("remotes")
# remotes::install_github("GIScience/openrouteservice-r")


# Load libraries
library(htmlwidgets)
library(leaflet)
library(openrouteservice)


# Set API key for Openrouteservice
# Get key at https://openrouteservice.org/plans/
ors_api_key("your_key")


# Set coordinates for start and end points (From Ystad to Linkoping, Sweden)
coordinates <- list(c(13.815941, 55.433299), c(15.632043, 58.403825))


# Create route
route_walking <- ors_directions(coordinates, profile="foot-walking")
route_car <- ors_directions(coordinates, profile="driving-car")


# View route on Leaflet map
Openrouteservice_routes = leaflet() %>%
  addTiles() %>%
  addGeoJSON(route_walking, fill=FALSE, color = "BLUE", group = "Walk") %>%
  addGeoJSON(route_car, fill=FALSE, color = "RED", group = "Car") %>%
  
  # Layers control
  addLayersControl(
    overlayGroups = c("Walk", "Car"),
    options = layersControlOptions(collapsed = FALSE)
  ) %>%   
  fitBBox(route_walking$bbox)


# Render Leaflet map
Openrouteservice_routes


# Save map to disk
saveWidget(widget = Openrouteservice_routes, file = "Openrouteservice_routes.html")

Leave a Reply

Your email address will not be published. Required fields are marked *

Please reload

Please Wait