| Title: | Download, Model and Analyze 'OpenStreetMap' Street Networks |
|---|---|
| Description: | A 'tidyverse'-friendly toolkit, inspired by the 'OSMnx' 'Python' library, to download, model, simplify, analyze and visualize street networks and other geospatial features from 'OpenStreetMap'. Build routable graphs from a place name, address, point or bounding box; simplify topology; compute shortest paths, isochrones and urban metrics (intersection density, circuity, street-orientation entropy, centrality); and export to 'sf', 'sfnetworks' and 'MapLibre'. Heavy graph computation is performed by a bundled 'Rust' core. |
| Authors: | Andre Leite [aut, cre], Marcos Wasilew [aut], Hugo Vasconcelos [aut], Carlos Amorim [aut], Diogo Bezerra [aut], StrategicProjects [cph, fnd], The extendr authors [cph] (Bundled Rust crates extendr-api, extendr-ffi, extendr-macros), David Tolnay [cph] (Bundled Rust crates proc-macro2, quote, syn, paste, readonly, unicode-ident), Alex Crichton [cph] (Bundled Rust crate proc-macro2), Marvin Loebel [cph] (Bundled Rust crate lazy_static), Aleksey Kladov [cph] (Bundled Rust crate once_cell), Unicode, Inc. [cph] (Bundled Rust crate unicode-ident (Unicode-3.0 data tables)) |
| Maintainer: | Andre Leite <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.1.1 |
| Built: | 2026-07-06 09:06:22 UTC |
| Source: | https://github.com/strategicprojects/osmnxr |
osm_graph for examples and testsBuilds a tiny n x n regular street grid as an osm_graph, with no
network access. Edges are bidirectional and weighted by their planar length.
Useful for examples, tests and learning the API offline.
example_osm_graph(n = 4, spacing = 100)example_osm_graph(n = 4, spacing = 100)
n |
Grid size; the network has |
spacing |
Distance between adjacent nodes, in CRS units. Default |
An osm_graph in an arbitrary projected CRS.
g <- example_osm_graph() g ox_basic_stats(g)g <- example_osm_graph() g ox_basic_stats(g)
osm_graph
Test whether an object is an osm_graph
is_osm_graph(x)is_osm_graph(x)
x |
An object. |
A logical scalar.
osm_graph
Low-level constructor wrapping tidy sf nodes and edges into the central
osm_graph object used across the package. Most users obtain an osm_graph
from ox_graph_from_place() and friends rather than calling this directly.
new_osm_graph(nodes, edges, meta = list())new_osm_graph(nodes, edges, meta = list())
nodes |
An |
edges |
An |
meta |
A named list of metadata (e.g. |
An object of class osm_graph.
Assigns a free-flow speed (km/h) to every edge based on its highway class,
adding a speed_kph column. Unknown classes get fallback.
ox_add_edge_speeds(g, speeds = NULL, fallback = 40)ox_add_edge_speeds(g, speeds = NULL, fallback = 40)
g |
An osm_graph. |
speeds |
Optional named numeric vector of |
fallback |
Speed (km/h) for edges with no matching class. Default |
The osm_graph with a speed_kph edge column.
g <- example_osm_graph() g <- ox_add_edge_speeds(g, speeds = c(residential = 25)) head(g$edges$speed_kph)g <- example_osm_graph() g <- ox_add_edge_speeds(g, speeds = c(residential = 25)) head(g$edges$speed_kph)
Adds a travel_time edge column (in seconds) from edge length (metres) and
speed_kph. Speeds are added with ox_add_edge_speeds() first if missing.
The resulting column can be used as a routing weight for time-based
shortest paths and isochrones.
ox_add_edge_travel_times(g)ox_add_edge_travel_times(g)
g |
An osm_graph. |
The osm_graph with speed_kph and travel_time
edge columns.
g <- example_osm_graph() g <- ox_add_edge_travel_times(g) from <- ox_nearest_nodes(g, 0, 0) to <- ox_nearest_nodes(g, 300, 300) ox_shortest_path(g, from, to, weight = "travel_time")g <- example_osm_graph() g <- ox_add_edge_travel_times(g) from <- ox_nearest_nodes(g, 0, 0) to <- ox_nearest_nodes(g, 300, 300) ox_shortest_path(g, from, to, weight = "travel_time")
dodgr graphReturns a data.frame in the column layout expected by the dodgr routing
package (from_id, from_lon, from_lat, to_id, to_lon, to_lat,
d), suitable for dodgr::dodgr_dists() and friends.
ox_as_dodgr(g, weight = "length")ox_as_dodgr(g, weight = "length")
g |
An osm_graph. |
weight |
Edge column used as the distance/weight |
A data.frame dodgr graph.
g <- example_osm_graph() head(ox_as_dodgr(g))g <- example_osm_graph() head(ox_as_dodgr(g))
sf nodes and edges from an osm_graph
Extract sf nodes and edges from an osm_graph
ox_as_sf(g)ox_as_sf(g)
g |
An |
A named list with sf elements nodes and edges.
g <- example_osm_graph() parts <- ox_as_sf(g) parts$edgesg <- example_osm_graph() parts <- ox_as_sf(g) parts$edges
sfnetwork
Returns the graph as a sfnetworks::sfnetwork() object, ready for the
sfnetworks/tidygraph spatial-network workflow.
ox_as_sfnetwork(g, directed = TRUE)ox_as_sfnetwork(g, directed = TRUE)
g |
An osm_graph. |
directed |
Build a directed network. Default |
An sfnetwork.
g <- example_osm_graph() ox_as_sfnetwork(g)g <- example_osm_graph() ox_as_sfnetwork(g)
tidygraph table graphReturns the graph as a tidygraph::tbl_graph(), dropping geometry (node
coordinates are kept as x/y columns).
ox_as_tidygraph(g, directed = TRUE)ox_as_tidygraph(g, directed = TRUE)
g |
An osm_graph. |
directed |
Build a directed graph. Default |
A tbl_graph.
g <- example_osm_graph() ox_as_tidygraph(g)g <- example_osm_graph() ox_as_tidygraph(g)
Summary measures for an osm_graph: node and edge counts, total and mean
edge length, mean out-degree, self-loop count and average circuity.
Computation is performed by the bundled Rust core.
ox_basic_stats(g, weight = "length")ox_basic_stats(g, weight = "length")
g |
An osm_graph. |
weight |
Edge column used as length/weight. Default |
A one-row tibble of statistics.
g <- example_osm_graph() ox_basic_stats(g)g <- example_osm_graph() ox_basic_stats(g)
Initial compass bearing (degrees clockwise from north) of each edge, from its first to its last coordinate. Geographic coordinates are used; projected graphs are transformed to EPSG:4326 first.
ox_bearings(g)ox_bearings(g)
g |
An osm_graph. |
A numeric vector of bearings, one per edge.
g <- example_osm_graph() head(ox_bearings(g))g <- example_osm_graph() head(ox_bearings(g))
Computes betweenness and/or closeness centrality for every node, using the Rust core (Brandes' algorithm for betweenness; one Dijkstra per node for closeness).
ox_centrality( g, type = c("betweenness", "closeness"), weight = "length", normalized = TRUE )ox_centrality( g, type = c("betweenness", "closeness"), weight = "length", normalized = TRUE )
g |
An osm_graph. |
type |
Centrality measures to compute: any of |
weight |
Edge column used as weight. Default |
normalized |
Scale scores for comparability across graphs. Betweenness
is divided by |
A tibble with column osmid plus one column per
requested measure.
g <- example_osm_graph(n = 4) ox_centrality(g, type = "betweenness")g <- example_osm_graph(n = 4) ox_centrality(g, type = "betweenness")
The ratio of total edge length to total straight-line (great-circle for
geographic CRS, Euclidean for projected) distance between edge endpoints. A
value of 1 means perfectly straight streets; higher values indicate more
winding networks.
ox_circuity(g)ox_circuity(g)
g |
An osm_graph. |
A numeric scalar (>= 1).
g <- example_osm_graph() ox_circuity(g)g <- example_osm_graph() ox_circuity(g)
Empties the in-memory cache of downloaded OpenStreetMap responses.
ox_clear_cache()ox_clear_cache()
Invisibly NULL.
ox_clear_cache()ox_clear_cache()
Merges groups of nodes lying within tolerance of one another into single
nodes placed at the group centroid, then rewrites edges to the consolidated
nodes and drops the resulting self-loops. Useful for collapsing the multiple
OSM nodes that represent one complex junction (e.g. dual carriageways).
ox_consolidate_intersections(g, tolerance = 10)ox_consolidate_intersections(g, tolerance = 10)
g |
An osm_graph. |
tolerance |
Distance below which nodes are merged, in CRS units.
Default |
Clustering uses sf::st_is_within_distance(); connected components are found
by the Rust core. tolerance is in the units of the graph CRS, so project
the graph first (e.g. to a metric CRS) for a meaningful distance.
A consolidated osm_graph (with meta$consolidated = TRUE).
g <- example_osm_graph(n = 4, spacing = 100) # nothing is within 10 units here, so the graph is unchanged ox_consolidate_intersections(g, tolerance = 10)g <- example_osm_graph(n = 4, spacing = 100) # nothing is within 10 units here, so the graph is unchanged ox_consolidate_intersections(g, tolerance = 10)
Computes the matrix of minimum-weight distances between every from node and
every to node (Rust core; one Dijkstra per source).
ox_distance_matrix(g, from, to = from, weight = "length")ox_distance_matrix(g, from, to = from, weight = "length")
g |
An osm_graph. |
from |
Node |
to |
Node |
weight |
Edge column used as weight. Default |
A numeric matrix (length(from) x length(to)) with osmid
dimnames; Inf marks unreachable pairs.
g <- example_osm_graph(n = 3) nodes <- g$nodes$osmid ox_distance_matrix(g, from = nodes[1:2], to = nodes[3:4])g <- example_osm_graph(n = 3) nodes <- g$nodes$osmid ox_distance_matrix(g, from = nodes[1:2], to = nodes[3:4])
Minimum-weight distance from from to every node in the graph.
ox_distances(g, from, weight = "length")ox_distances(g, from, weight = "length")
g |
An osm_graph. |
from |
A node |
weight |
Edge column used as weight. Default |
A tibble with columns osmid and distance
(Inf for unreachable nodes).
g <- example_osm_graph() ox_distances(g, ox_nearest_nodes(g, 0, 0))g <- example_osm_graph() ox_distances(g, ox_nearest_nodes(g, 0, 0))
Loads a small, real street network shipped with the package (downloaded once from OpenStreetMap and simplified) so that examples and vignettes can show real analyses without network access.
ox_example(name = c("olinda", "manhattan", "rome"))ox_example(name = c("olinda", "manhattan", "rome"))
name |
Which network to load (all drivable, simplified):
|
An osm_graph.
g <- ox_example("olinda") g ox_basic_stats(g)g <- ox_example("olinda") g ox_basic_stats(g)
Queries OpenStreetMap (via Overpass) for elements matching tags — points of
interest, amenities, buildings, transit stops, and so on — returning them as
an sf of points (ways and relations are represented by their centroid).
ox_features_from_bbox(bbox, tags)ox_features_from_bbox(bbox, tags)
bbox |
Numeric |
tags |
Named list of OSM tag filters. Each element is either |
An sf of POINT features with osm_type, osm_id and one column
per tag encountered.
bbox <- c(-34.91, -8.07, -34.87, -8.04) ox_features_from_bbox(bbox, tags = list(amenity = "school"))bbox <- c(-34.91, -8.07, -34.87, -8.04) ox_features_from_bbox(bbox, tags = list(amenity = "school"))
Geocodes query with ox_geocode() and downloads matching features around
it. See ox_features_from_bbox() for the tags format.
ox_features_from_place(query, tags, dist = 2000)ox_features_from_place(query, tags, dist = 2000)
query |
A place name, e.g. |
tags |
Named list of OSM tag filters. |
dist |
Search half-width in metres around the geocoded point. Default
|
An sf of POINT features.
ox_features_from_place("Olinda, Brazil", tags = list(amenity = "hospital"))ox_features_from_place("Olinda, Brazil", tags = list(amenity = "hospital"))
Resolve a free-form query to coordinates and metadata using the OpenStreetMap Nominatim service.
ox_geocode(query, limit = 1)ox_geocode(query, limit = 1)
query |
A character scalar, e.g. |
limit |
Maximum number of results. Default |
A tibble with columns display_name, lat,
lon, osm_type, osm_id and class.
ox_geocode("Recife, Brazil")ox_geocode("Recife, Brazil")
sf boundaryLike ox_geocode() but returns the place geometry (boundary polygon when
available, otherwise a point) as an sf object.
ox_geocode_to_sf(query, limit = 1)ox_geocode_to_sf(query, limit = 1)
query |
A character scalar, e.g. |
limit |
Maximum number of results. Default |
An sf object (one row per result) in EPSG:4326.
ox_geocode_to_sf("Recife, Brazil")ox_geocode_to_sf("Recife, Brazil")
Download a street network around an address
ox_graph_from_address(address, dist = 1000, network_type = "drive")ox_graph_from_address(address, dist = 1000, network_type = "drive")
address |
A street address. |
dist |
Buffer half-width in metres. Default |
network_type |
One of |
An osm_graph.
g <- ox_graph_from_address("Marco Zero, Recife", dist = 600)g <- ox_graph_from_address("Marco Zero, Recife", dist = 600)
Download a street network within a bounding box
ox_graph_from_bbox(bbox, network_type = "drive")ox_graph_from_bbox(bbox, network_type = "drive")
bbox |
Numeric vector |
network_type |
One of |
An osm_graph.
bbox <- c(-34.91, -8.07, -34.87, -8.04) g <- ox_graph_from_bbox(bbox, network_type = "drive")bbox <- c(-34.91, -8.07, -34.87, -8.04) g <- ox_graph_from_bbox(bbox, network_type = "drive")
Geocodes query with ox_geocode() and downloads the street network within
the bounding box of the matched place.
ox_graph_from_place(query, network_type = "drive")ox_graph_from_place(query, network_type = "drive")
query |
A place name, e.g. |
network_type |
One of |
An osm_graph.
g <- ox_graph_from_place("Olinda, Brazil", network_type = "drive")g <- ox_graph_from_place("Olinda, Brazil", network_type = "drive")
Download a street network around a point
ox_graph_from_point(point, dist = 1000, network_type = "drive")ox_graph_from_point(point, dist = 1000, network_type = "drive")
point |
Numeric |
dist |
Buffer half-width in metres (a square bounding box of side
|
network_type |
One of |
An osm_graph.
g <- ox_graph_from_point(c(-34.89, -8.05), dist = 800)g <- ox_graph_from_point(c(-34.89, -8.05), dist = 800)
For one or more origin nodes, finds the set of nodes reachable within each
cutoff (by the chosen edge weight — distance or, with
ox_add_edge_travel_times(), travel time) and returns a polygon per cutoff:
the hull of the reachable nodes. With several origins, reachability is the
minimum cost from any origin.
ox_isochrone(g, center, cutoffs, weight = "length", ratio = 0.4)ox_isochrone(g, center, cutoffs, weight = "length", ratio = 0.4)
g |
An osm_graph. |
center |
One or more origin node |
cutoffs |
Numeric vector of cutoff values, in the units of |
weight |
Edge column used as cost. Default |
ratio |
Concavity for |
Reachable sets come from the Rust Dijkstra core; the hull is built with
sf::st_concave_hull() when available (GEOS >= 3.11), falling back to a
convex hull. For metric cutoffs, project the graph to a metric CRS first.
An sf object with one polygon row per cutoff (columns cutoff,
n_nodes, geometry), ordered from largest to smallest cutoff so smaller
areas draw on top.
g <- example_osm_graph(n = 6, spacing = 100) center <- ox_nearest_nodes(g, 250, 250) iso <- ox_isochrone(g, center, cutoffs = c(100, 300)) isog <- example_osm_graph(n = 6, spacing = 100) center <- ox_nearest_nodes(g, 250, 250) iso <- ox_isochrone(g, center, cutoffs = c(100, 300)) iso
Computes up to k loopless shortest paths from from to to using Yen's
algorithm in the Rust core. Useful for route alternatives.
ox_k_shortest_paths(g, from, to, k = 3, weight = "length")ox_k_shortest_paths(g, from, to, k = 3, weight = "length")
g |
An osm_graph. |
from, to
|
Node |
k |
Number of paths to return. Default |
weight |
Edge column used as weight. Default |
A tibble with one row per path: rank, cost and
a list-column path of node osmids, ordered by increasing cost. Fewer
than k rows are returned when fewer distinct paths exist.
g <- example_osm_graph() from <- ox_nearest_nodes(g, 0, 0) to <- ox_nearest_nodes(g, 200, 200) ox_k_shortest_paths(g, from, to, k = 3)g <- example_osm_graph() from <- ox_nearest_nodes(g, 0, 0) to <- ox_nearest_nodes(g, 200, 200) ox_k_shortest_paths(g, from, to, k = 3)
Reads a GraphML file written by ox_save_graphml() back into an
osm_graph, restoring node coordinates, edge attributes and
edge geometry (from the stored WKT).
ox_load_graphml(path)ox_load_graphml(path)
path |
Path to a |
An osm_graph.
g <- example_osm_graph() f <- tempfile(fileext = ".graphml") ox_save_graphml(g, f) ox_load_graphml(f)g <- example_osm_graph() f <- tempfile(fileext = ".graphml") ox_save_graphml(g, f) ox_load_graphml(f)
Returns, for each supplied coordinate, the graph edge closest in planar distance.
ox_nearest_edges(g, x, y)ox_nearest_edges(g, x, y)
g |
An osm_graph. |
x, y
|
Numeric vectors of coordinates in the graph's CRS. |
An sf subset of g$edges, one row per input point.
g <- example_osm_graph() ox_nearest_edges(g, x = 50, y = 0)g <- example_osm_graph() ox_nearest_edges(g, x = 50, y = 0)
Returns the osmid of the graph node closest (in planar distance) to each
supplied coordinate.
ox_nearest_nodes(g, x, y)ox_nearest_nodes(g, x, y)
g |
An osm_graph. |
x, y
|
Numeric vectors of coordinates in the graph's CRS. |
An integer/numeric vector of node osmids, one per input point.
g <- example_osm_graph() ox_nearest_nodes(g, x = 0, y = 0)g <- example_osm_graph() ox_nearest_nodes(g, x = 0, y = 0)
Shannon entropy (in nats) of the distribution of edge compass bearings, binned into equal sectors. Higher values indicate a more disordered (organic) network; lower values a more ordered (gridiron) one.
ox_orientation_entropy(x, num_bins = 36)ox_orientation_entropy(x, num_bins = 36)
x |
An osm_graph or a numeric vector of bearings
(degrees), e.g. from |
num_bins |
Number of equal bearing sectors over |
A numeric scalar (entropy in nats).
g <- example_osm_graph() ox_orientation_entropy(g)g <- example_osm_graph() ox_orientation_entropy(g)
Draws a figure-ground diagram: the streets in a single colour on a solid background, with no axes or margins. Cropping different places to the same extent makes their network form directly comparable, as in Boeing (2025).
ox_plot_figure_ground(g, bg = "black", col = "white", lwd = 1.2, title = NULL)ox_plot_figure_ground(g, bg = "black", col = "white", lwd = 1.2, title = NULL)
g |
An osm_graph. |
bg, col
|
Background and street colours. Default white-on-black. |
lwd |
Street line width. Default |
title |
Optional panel title. |
Invisibly, the osm_graph.
g <- example_osm_graph() ox_plot_figure_ground(g)g <- example_osm_graph() ox_plot_figure_ground(g)
Draws a polar histogram (rose plot) of edge compass bearings, the standard
visual summary of a street network's orientation order. Requires ggplot2.
ox_plot_orientation( x, num_bins = 36, fill = "#0d3b66", title = "Street orientation" )ox_plot_orientation( x, num_bins = 36, fill = "#0d3b66", title = "Street orientation" )
x |
An osm_graph or a numeric vector of bearings
(degrees), e.g. from |
num_bins |
Number of equal bearing sectors. Default |
fill |
Bar fill colour. Default the package blue. |
title |
Optional plot title. |
A ggplot object.
g <- example_osm_graph() ox_plot_orientation(g)g <- example_osm_graph() ox_plot_orientation(g)
Writes the graph to a GraphML file compatible with OSMnx / NetworkX / Gephi.
Edge geometry is preserved losslessly as a WKT attribute, so the graph
round-trips through ox_load_graphml().
ox_save_graphml(g, path)ox_save_graphml(g, path)
g |
An osm_graph. |
path |
Output |
path, invisibly.
g <- example_osm_graph() f <- tempfile(fileext = ".graphml") ox_save_graphml(g, f)g <- example_osm_graph() f <- tempfile(fileext = ".graphml") ox_save_graphml(g, f)
Configure the Overpass and Nominatim endpoints, HTTP behaviour and caching
used by all ox_* download functions. Called with no arguments it returns
the current settings as a list; called with named arguments it updates them
and returns the previous values invisibly.
ox_settings(...)ox_settings(...)
... |
Named settings to update. Recognised names: |
A named list of settings (current values, or the previous values invisibly when updating).
ox_settings() old <- ox_settings(timeout = 300) ox_settings(timeout = old$timeout) # restoreox_settings() old <- ox_settings(timeout = 300) ox_settings(timeout = old$timeout) # restore
Computes the minimum-weight path from from to to using Dijkstra's
algorithm in the Rust core.
ox_shortest_path(g, from, to, weight = "length")ox_shortest_path(g, from, to, weight = "length")
g |
An osm_graph. |
from, to
|
Node |
weight |
Edge column used as weight. Default |
A vector of node osmids describing the path (length 0 if the
target is unreachable).
g <- example_osm_graph() from <- ox_nearest_nodes(g, 0, 0) to <- ox_nearest_nodes(g, 300, 300) ox_shortest_path(g, from, to)g <- example_osm_graph() from <- ox_nearest_nodes(g, 0, 0) to <- ox_nearest_nodes(g, 300, 300) ox_shortest_path(g, from, to)
Removes interstitial (degree-2) nodes that merely shape the geometry of a
street, merging each maximal chain of such nodes into a single edge whose
geometry follows the original points and whose length is the sum of the
merged segments. Only true endpoints and intersections are kept as nodes.
ox_simplify(g)ox_simplify(g)
g |
An unsimplified osm_graph. |
The topology walk is performed by the Rust core; geometry is rebuilt with
sf. Downloaded graphs are unsimplified by default; this is the standard
cleanup step before analysis.
A simplified osm_graph (with meta$simplified = TRUE).
g <- example_osm_graph() ox_simplify(g) # already simplified: returned unchangedg <- example_osm_graph() ox_simplify(g) # already simplified: returned unchanged
Writes the graph's edges (or nodes) to a GeoJSON file via sf::st_write().
Geometry is transformed to EPSG:4326, the GeoJSON standard CRS.
ox_to_geojson(g, path, layer = c("edges", "nodes"))ox_to_geojson(g, path, layer = c("edges", "nodes"))
g |
An osm_graph. |
path |
Output file path. |
layer |
Which layer to write: |
path, invisibly.
g <- example_osm_graph() ox_to_geojson(g, tempfile(fileext = ".geojson"))g <- example_osm_graph() ox_to_geojson(g, tempfile(fileext = ".geojson"))
Writes the edges to a GeoJSON file and returns a MapLibre GL JS style
fragment (a list with sources and layers) that references it, ready to
merge into a map style. Serialize with, e.g., jsonlite::toJSON(..., auto_unbox = TRUE).
ox_to_maplibre( g, path, source_id = "osmnxr", layer_id = "streets", url = basename(path) )ox_to_maplibre( g, path, source_id = "osmnxr", layer_id = "streets", url = basename(path) )
g |
An osm_graph. |
path |
GeoJSON output path for the edge data. |
source_id, layer_id
|
Identifiers for the MapLibre source and layer. |
url |
URL the style should use to fetch the data. Defaults to
|
A named list with sources and layers, invisibly written data to
path.
g <- example_osm_graph() style <- ox_to_maplibre(g, tempfile(fileext = ".geojson")) names(style)g <- example_osm_graph() style <- ox_to_maplibre(g, tempfile(fileext = ".geojson")) names(style)
osm_graph
Draws the street-network edges (and optionally nodes) using base sf
plotting.
## S3 method for class 'osm_graph' plot(x, nodes = FALSE, col = "#0d3b66", lwd = 0.7, ...)## S3 method for class 'osm_graph' plot(x, nodes = FALSE, col = "#0d3b66", lwd = 0.7, ...)
x |
An |
nodes |
Logical; overlay node points. Default |
col, lwd
|
Passed to the edge geometry plot. |
... |
Further arguments passed to |
Invisibly, the osm_graph.