Search code examples
rcsvdistanceosrm

Calculating route distance from coordinates in CSV in R


I would like to calculate the route distance of coordinate to coordinate from OSRM (although I'm open to other services).

For example, a row will have a "from" and "to" coordinate, and instead of getting the point-to-point distance, use the routing to have a more accurate picture of the distance traveled.

I've tried every iteration of the script provided here, and have cut my data to be 25 rows.

https://www.rdocumentation.org/packages/osrm/versions/3.3.0/topics/osrmTable

# Set the working directory
setwd("C:/Users/...")

# Load libraries
library(dplyr)
library(osrm)
library(geosphere)

# Bring in the data
mydata <- read.csv("coordinates.csv", stringsAsFactors=FALSE)

# Check and eliminate the rows that don't have location information 
mydata <- mydata[!is.na(mydata$fromlat),]
mydata <- subset(mydata, fromlat!=0)

mydata <- mydata[!is.na(mydata$tolat),]
mydata <- subset(mydata, tolat!=0)

# Create date for route
src <- mydata[c(7,10,9)]
dst <- mydata[c(7,12,11)] 

# Travel time matrix with different sets of origins and destinations
route <- osrmTable(src = src, dst = dst, exclude = NULL,
                   gepaf = FALSE, measure = "distance")

Ideally, I would like for a new column to be put in the data that has the distance between the two coordinates using the routing.

I've figured it out for a point-to-point distance, but I am having difficulty doing it with routing.

I get this message after I run my script:

The OSRM server returned an error:
Error in function (type, msg, asError = TRUE) : Failed to connect to router.project-osrm.org port 80: Timed out

Update: I've tried using gmapsdistance, and am also getting a connectivity issue. I suspect it's a workplace firewall issue. I will look into it and will post the results.


Solution

  • Indeed I am behind a firewall that is blocking access to OSRM. To solve this problem, I am running an instance of R through RStudio Cloud.