First, let’s load packages osmar, leaflet and igraph
library(osmar)
library(leaflet)
library(igraph)
Then, using osmar, let’s load some OSM data for Belgrade, Serbia
nbgd5k <- get_osm(center_bbox(20.41,44.82, 5000, 5000),all=True)
Then let’s subset the streets network:
hways_nbgd <- subset(nbgd5k, way_ids = find(nbgd5k, way(tags(k == "highway"))))
hways <- find(hways_nbgd, way(tags(k == "highway")))
hways <- find_down(nbgd5k, way(hways))
hways_nbgd <- subset(nbgd5k, ids = hways)
hways_nbgd
## osmar object
## 19278 nodes, 3434 ways, 0 relations
Select start and end node… (in this case start node will be a bus stop outside of a student dorm and end node will be in a popular mall)
hway_start_node <- local({
id <- find(nbgd5k, node(tags(v == "Studentski grad")))[3]
find_nearest_node(nbgd5k, id, way(tags(k == "highway")))})
hway_start <- subset(nbgd5k, node(hway_start_node))
hway_end_node <- local({
id <- find(nbgd5k, node(tags(v == "Colmar")))[1]
find_nearest_node(nbgd5k, id, way(tags(k == "highway")))
})
hway_end <- subset(nbgd5k, node(hway_end_node))
Then let’s convert osmart object (network of streets) to an igraph graph object
streetz_nbg<-as_igraph(hways_nbgd)
and find the shortest path
route <- get.shortest.paths(streetz_nbg,
from = as.character(hway_start_node),
to = as.character(hway_end_node))[[1]]
route_nodes <- as.numeric(V(streetz_nbg)[as.integer(route[[1]])]$name)
route_ids <- find_up(hways_nbgd, node(route_nodes))
route_nbg <- subset(hways_nbgd, ids = route_ids)
After we find the shortest path we can plot it using leaflet package:
leaflet()%>%addTiles()%>%
setView(20.41, lat=44.82, zoom=14)%>%addPolylines(data=as_sp(route_nbg,"lines"))