ropenstreetmapigraphosmar

What is the basis for the weight function of igraph route object created from osmar object?


I was wondering how is the weight value calculated while creating igraph route object from osmar object? Is there a maximum?

library(osmar)
library(igraph)
src <- osmsource_api(url = "https://api.openstreetmap.org/api/0.6/")
muc_bbox <- center_bbox(11.575278, 48.137222, 1000, 1000)
muc <- get_osm(muc_bbox, src)

hways <- subset(muc, way_ids = find(muc, way(tags(k == "highway"))))
hways <- find(hways, way(tags(k == "name")))
hways <- find_down(muc, way(hways))
hways <- subset(muc, ids = hways)

id<-find(muc, node(tags(v %agrep% "Sendlinger Tor")))[1]
hway_start_node <-find_nearest_node(muc, id, way(tags(k == "highway"))) 
hway_start <- subset(muc, node(hway_start_node))

id <- find(muc, node(attrs(lon > 11.58 & lat > 48.15)))[1]
hway_end_node <- find_nearest_node(muc, id, way(tags(k == "highway")))
hway_end <- subset(muc, node(hway_end_node))

### Create street graph ----
gr <- as.undirected(as_igraph(hways))

### Compute shortest route: ----
# Calculate route
route <- function(start_node,end_node) {
get.shortest.paths(gr,
                     from = as.character(start_node),
                     to = as.character(end_node), 
                     mode = "all")[[1]][[1]]}
#get Weight value
r <- route(hway_start_node,hway_end_node)
max(E(gr)[r]$weight)

Thank you! Best regards.


Solution

  • For most Edges, Weight is simply the distance (in meters) between the Nodes of the Edge:

    # Get nodes Latitude & Longitude
    nodes.coords <- hways$nodes$attrs[, c("lon", "lat")]
    nodes.coords$id<- as.character(hways$nodes$attrs$id)
    setDT(nodes.coords)
    
    # Put two Nodes from an Edge together
    edges_data_frame <- get.data.frame(gr, what = "edges")
    datafrom <- nodes.coords[edges_data_frame,on = .(id = from)][,.(lonfrom = lon,latfrom=lat,weight,id,to)]
    datafromto <- nodes.coords[datafrom,on = .(id = to)][,.(lonfrom, latfrom,lonto = lon,latto=lat,weight)]
    
    # Calculate distance between nodes
    datafromto[,dist:=geosphere::distHaversine(cbind(lonfrom,latfrom),cbind(lonto,latto))]
    
    # Check percentage of Weights different of distance
    nrow( datafromto[weight!=dist]) / nrow(datafromto)
    
    [1] 0.03979914
    

    This result shows that for 96% of Edges, Weight = distance between Nodes.
    I don't know the reason why this is not the case for the remaining 4%.