Search code examples
rosrm

Calculating distance of multiple coordinates in R


As written in the title I want to calculate the distance from all gas stations in my hometown to the two motorway accesses around here using the package osrm.

stations_ms contains Latitude & Longitude for the gas stations and highway_ms.df contains the lat & long for the motorway accesses.

Calculating the distance for just one row of my dataset is no problem, but I am not able to create a loop/function, which does it for every row.

Here is my code:

route4 <-  osrmRoute(src = c(stations_ms$longitude[1], stations_ms$latitude[1]), 
                    dst = highway_ms.df[1,],
                    overview = "FALSE")

for (i in 1:nrow(stations_ms)) {
 route[i] <- osrmRoute(src = c(stations_ms$longitude[i], stations_ms$latitude[i]),
                       dst = highway_ms.df[1,],
                       overwiew = "FALSE")
}
```

Maybe someone can help me :)

Solution

  • Here is a workable example that might be helpful.

    The overview in osrmRoute has the following options:

    "full", "simplified" or FALSE. Use "full" to return the detailed geometry, use "simplified" to return a simplified geometry, use FALSE to return only time and distance.

    If you only want time and distance, using FALSE should work fine. My comment was in regard to spelling (had a "w" instead of a "v").

    I made up some example data:

    my_points <- data.frame(
      id = 1:3,
      longitude = c(13.4, 13.5, 13.3),
      latitude = c(52.4, 52.5, 52.3)
    )
    

    And wanted to find distances to a pharmacy in Berlin (using apotheke.df that comes with the osrm package). You could do:

    library(osrm)
    
    route <- list()
    for (i in 1:nrow(my_points)) {
      route[[i]] <- osrmRoute(src = c(my_points$longitude[i], my_points$latitude[i]),
                              dst = apotheke.df[1,],
                              overview = FALSE)
    }
    

    This starts with an empty list called route. Then, we fill in each list element with both time and duration. The end result is the following list:

    R> route
    
    [[1]]
    duration distance 
       20.56    11.77 
    
    [[2]]
    duration distance 
       17.38     7.63 
    
    [[3]]
    duration distance 
       33.12    27.45
    

    Which can be converted to a matrix or data frame (in this case, I made a matrix):

    R> do.call(rbind, route)
    
         duration distance
    [1,]    20.56    11.77
    [2,]    17.38     7.63
    [3,]    33.12    27.45