Loading library
pacman::p_load(
dodgr,
sf,
tidygraph,
igraph,
dplyr,
tibble,
ggplot2,
units,
tmap,
osmdata,
rgrass7,
link2GI,
nabor,
leaflet
)
Data
bb <- osmdata::getbb("glasgow uk") # bounding box
glasgow <- opq(bbox = bb) %>%
add_osm_feature(key = "highway") %>%
osmdata_sf() %>%
osm_poly2line()
glasgow <- glasgow$osm_lines %>% select(highway)
saveRDS(glasgow, "data/glasgow.rds")
# prepare graph (dodgr file)
graph.gla <- weight_streetnet(glasgow, wt_profile = "motorcar")
## x appears to have no ID column; sequential edge numbers will be used.
## The following highway types are present in data yet lack corresponding weight_profile values: construction, corridor, busway, NA, proposed, raceway, road, elevator, rest_area, traffic_island,
head(graph.gla)
## geom_num edge_id from_id from_lon from_lat to_id to_lon to_lat
## 1 1 1 411041 -4.333850 55.92826 939205471 -4.333674 55.92847
## 2 1 2 939205471 -4.333674 55.92847 411041 -4.333850 55.92826
## 3 1 3 939205471 -4.333674 55.92847 411038 -4.333525 55.92852
## 4 1 4 411038 -4.333525 55.92852 939205471 -4.333674 55.92847
## 5 1 5 411038 -4.333525 55.92852 411039 -4.332420 55.92851
## 6 1 6 411039 -4.332420 55.92851 411038 -4.333525 55.92852
## d d_weighted highway lanes way_id component time time_weighted
## 1 26.00342 52.00684 residential <NA> 1473 1 3.744492 7.488985
## 2 26.00342 52.00684 residential <NA> 1473 1 3.744492 7.488985
## 3 10.92954 21.85908 residential <NA> 1473 1 1.573854 3.147708
## 4 10.92954 21.85908 residential <NA> 1473 1 1.573854 3.147708
## 5 69.05958 138.11915 residential <NA> 1473 1 9.944579 19.889158
## 6 69.05958 138.11915 residential <NA> 1473 1 9.944579 19.889158
saveRDS(graph.gla, "data/glasgow_graph.rds")
Read processed files
glasgow <- readRDS("data/glasgow.rds")
graph <- readRDS("data/glasgow_graph.rds")
Shortest Path with dodgr package
# Set a sample of xy long lat
from <- sample(graph$from_id, size = 100)
to <- sample(graph$to_id, size = 80)
# shortest path
dp <- dodgr_paths(graph, from = from, to = to)
# assign verts into path
verts <- dodgr_vertices(graph)
path <- verts [match (dp [[1]] [[1]], verts$id), ]
head(path)
## id x y component n
## 98430 3813688935 -4.336729 55.98727 1 50295
## 98432 661015 -4.336373 55.98724 1 50296
## 98434 313758366 -4.335454 55.98714 1 50297
## 98436 313758367 -4.335045 55.98706 1 50298
## 98438 661016 -4.334643 55.98695 1 50299
## 98440 32320059 -4.334374 55.98692 1 50300
Mapping
dt <- st_as_sf(path, coords = c("x", "y"), crs = 4326)
dt <- dt[1:310, ]
# leaflet
leaflet() %>% addTiles() %>% addMarkers(data = dt)
# osm
osroute <- osrm::osrmRoute(loc = dt)
leaflet::leaflet(data = dt) %>%
addProviderTiles("CartoDB.Positron") %>%
addPolylines(data = osroute,
label = "OSRM engine",
color = "red")