Im calculating the shortest path between 2 points in sfnetwork my_sfn.
The calculated path consists of graph ids kept in variable paths and I and would like to get geometry (gps values) connected to those ids.
which is done with:
coordinates_of_the_path<-mclapply(paths,function(x) cbind(as.data.frame(st_coordinates(igraph::get.edge.attribute(graph = my_sfn, name = "geometry", index = x[1]))),id=x),mc.preschedule=TRUE, mc.cores = n.cores)
The whole block:
First I get open street map data:
library(sf)
library(tidygraph)
library(sfnetworks)
library(osmdata)
library(parallel)
library(data.table)
library(tictoc)
if ((n.cores <- detectCores()) > 4) n.cores <- 4
setDTthreads(threads = n.cores)
my_osm_data <- opq(bbox = c(11.68771, 47.75233, 12.35058, 48.19743 )) %>%
add_osm_feature(
key = 'highway',
value = c("trunk", "trunk_link", "primary","primary_link", "secondary", "secondary_link", "tertiary","tertiary_link", "residential", "unclassified")
) %>%
osmdata_sf(quiet = FALSE)
my_osm_data<-osmdata::osm_poly2line(my_osm_data)
my_roads <- my_osm_data$osm_lines[, c("osm_id","name")]
#my_roads <- st_geometry(my_osm_data$osm_lines)
my_sfn <- as_sfnetwork(my_roads, directed = FALSE, length_as_weight = TRUE)
Then I set the start and destination points:
start_point =st_sfc(st_point(c(11.829831, 48.110075)))
st_crs(start_point) = st_crs(my_sfn)
dest_point =st_sfc(st_point(c(12.20747, y = 47.83937)))
st_crs(dest_point) = st_crs(my_sfn)
Claculate a path:
paths = st_network_paths(my_sfn, from = start_point, to = dest_point)
paths = paths %>%
slice(1) %>%
pull(edge_paths) %>%
unlist()
And here I would like to get the geometry of this path.
coordinates_of_the_path<-mclapply(paths,function(x) cbind(as.data.frame(st_coordinates(igraph::get.edge.attribute(graph = my_sfn, name = "geometry", index = x[1]))),id=x),mc.preschedule=TRUE, mc.cores = n.cores)
But this last call takes far to long. Is there a way to make it faster?
I solved it by using the index in the last column in data.frame as index for the paths vector
coordinates_of_the_path<-as.data.frame(st_coordinates(igraph::get.edge.attribute(graph = my_sfn, name = "geometry", index = paths)))
coordinates_of_the_path<-cbind(coordinates_of_the_path,id=paths[coordinates_of_the_path$L1])