| Title: | An R Port of 'OSMnx' for 'OpenStreetMap' Street Networks |
| Version: | 0.1.6 |
| Description: | An R port of 'OSMnx', the 'Python' library by Geoff Boeing (Boeing, 2025, <doi:10.1111/gean.70009>), to download, model, simplify, analyze and visualize street networks and other geospatial features from 'OpenStreetMap'. The public interface, the modelling choices and the 'Overpass' queries are those of 'OSMnx', translated to a 'tidyverse'-friendly R interface; the port was written with the assistance of AI coding tools and is not affiliated with the 'OSMnx' project. 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 the bundled 'Rust' crate 'osmnxr-core'. |
| Copyright: | 'OSMnx', the work this package ports, is copyright (c) 2016-2026 Geoff Boeing and distributed under the MIT license; its notice is reproduced in inst/COPYRIGHTS. See inst/AUTHORS for the bundled 'Rust' crates. |
| Language: | en-US |
| License: | MIT + file LICENSE |
| URL: | https://github.com/StrategicProjects/osmnxr, https://strategicprojects.github.io/osmnxr/ |
| BugReports: | https://github.com/StrategicProjects/osmnxr/issues |
| Encoding: | UTF-8 |
| RoxygenNote: | 8.0.0 |
| SystemRequirements: | Cargo (Rust's package manager), rustc |
| Depends: | R (≥ 4.2) |
| Imports: | cli, glue, httr2 (≥ 1.0.0), purrr, rlang (≥ 1.1.0), sf, tibble |
| Suggests: | dodgr, ggplot2, jsonlite, knitr, rmarkdown, sfnetworks, testthat (≥ 3.0.0), tidygraph, units, xml2 |
| Config/testthat/edition: | 3 |
| VignetteBuilder: | knitr |
| Config/rextendr/version: | 0.5.0 |
| NeedsCompilation: | yes |
| Packaged: | 2026-11-29 20:22:32 UTC; leite |
| Author: | André Leite |
| Maintainer: | André Leite <leite@castlab.org> |
| Repository: | CRAN |
| Date/Publication: | 2026-11-30 15:50:42 UTC |
osmnxr: an R port of OSMnx
Description
An R port of OSMnx, the Python library by Geoff Boeing, to download,
model, simplify, analyze and visualize street networks and other
geospatial features from OpenStreetMap. The design is that of OSMnx: the
public API translates its function names (graph_from_place becomes
ox_graph_from_place()), and its modelling choices (network types, the
Overpass filters, topology simplification, intersection consolidation,
the urban metrics) are reproduced. No Python runtime is involved: the R
layer was written for this package and the graph algorithms run in the
bundled Rust crate osmnxr-core
(https://strategicprojects.github.io/osmnxr-core/). The port was made
with the assistance of AI coding tools. osmnxr is not affiliated with or
endorsed by the OSMnx project; OSMnx's copyright notice is in
system.file("COPYRIGHTS", package = "osmnxr").
Details
If you use osmnxr, please cite the OSMnx paper below.
Author(s)
Maintainer: André Leite leite@castlab.org (ORCID) [translator]
Authors:
André Leite leite@castlab.org (ORCID) [translator]
Marcos Wasiliew marcos.wasiliew@gmail.com (ORCID) [translator]
Hugo Vasconcelos hugo.vasconcelos@ufpe.br (ORCID) [translator]
Carlos Amorim carlos.agaf@ufpe.br (ORCID) [translator]
Diogo Bezerra diogo.bezerra@ufpe.br (ORCID) [translator]
Júlia Nascimento Barreto juliabarreto@gd.seplag.pe.gov.br (ORCID) [translator]
Geoff Boeing (ORCID) (Author and copyright holder of 'OSMnx', the 'Python' library that this package ports to R) [copyright holder]
Other contributors:
Srikanth Komala Sheshachala sri.teach@gmail.com (Issue reports and feature proposals (GitHub: talegari)) [contributor]
StrategicProjects (Also copyright holder of the bundled Rust crate osmnxr-core) [copyright holder, funder]
The extendr authors (Bundled Rust crates extendr-api, extendr-ffi, extendr-macros) [copyright holder]
David Tolnay (Bundled Rust crates proc-macro2, quote, syn, paste, readonly, unicode-ident) [copyright holder]
Alex Crichton (Bundled Rust crate proc-macro2) [copyright holder]
Marvin Loebel (Bundled Rust crate lazy_static) [copyright holder]
Aleksey Kladov (Bundled Rust crate once_cell) [copyright holder]
Unicode, Inc. (Bundled Rust crate unicode-ident (Unicode-3.0 data tables)) [copyright holder]
References
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
See Also
OSMnx: https://osmnx.readthedocs.io/. The package website: https://strategicprojects.github.io/osmnxr/.
A small synthetic osm_graph for examples and tests
Description
Builds 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.
Usage
example_osm_graph(n = 4, spacing = 100)
Arguments
n |
Grid size; the network has |
spacing |
Distance between adjacent nodes, in CRS units. Default |
Value
An osm_graph in an arbitrary projected CRS.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
g
ox_basic_stats(g)
Test whether an object is an osm_graph
Description
Test whether an object is an osm_graph
Usage
is_osm_graph(x)
Arguments
x |
An object. |
Value
A logical scalar.
Construct an osm_graph
Description
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.
Usage
new_osm_graph(nodes, edges, meta = list())
Arguments
nodes |
An |
edges |
An |
meta |
A named list of metadata (e.g. |
Value
An object of class osm_graph.
Add edge penalties by road type
Description
Builds a per-edge penalty column from the edge highway class: each edge
gets factor * weight, where factor comes from the named penalties
vector (classes not listed get 0). The column quantifies how much of a
route runs on penalized road types, in the units of weight.
Usage
ox_add_edge_penalties(g, penalties, weight = "length", name = "penalty")
Arguments
g |
An osm_graph. |
penalties |
Named numeric vector of |
weight |
Edge column the factors multiply. Default |
name |
Name of the new edge column. Default |
Details
Two ways to use it:
-
Scalarized routing — add the penalty onto the routing weight (
g$edges$w <- g$edges$length + g$edges$penalty) and route onwwithox_shortest_path(): an ordinary shortest path that trades length against preference at a fixed rate. -
Constrained / Pareto routing — pass the column as the
resourceofox_route_constrained()orox_route_pareto(), e.g. "fastest route with at most 500 m on residential streets" (penalties = c(residential = 1),budget = 500).
Value
The osm_graph with the penalty edge column added.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
g <- ox_add_edge_penalties(g, c(residential = 1))
head(g$edges$penalty)
Add edge speeds
Description
Assigns a free-flow speed (km/h) to every edge based on its highway class,
adding a speed_kph column. Unknown classes get fallback.
Usage
ox_add_edge_speeds(g, speeds = NULL, fallback = 40)
Arguments
g |
An osm_graph. |
speeds |
Optional named numeric vector of |
fallback |
Speed (km/h) for edges with no matching class. Default |
Value
The osm_graph with a speed_kph edge column.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
g <- ox_add_edge_speeds(g, speeds = c(residential = 25))
head(g$edges$speed_kph)
Add edge travel times
Description
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.
Usage
ox_add_edge_travel_times(g)
Arguments
g |
An osm_graph. |
Value
The osm_graph with speed_kph and travel_time
edge columns.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
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")
Convert to a dodgr graph
Description
Returns 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.
Usage
ox_as_dodgr(g, weight = "length")
Arguments
g |
An osm_graph. |
weight |
Edge column used as the distance/weight |
Value
A data.frame dodgr graph.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
head(ox_as_dodgr(g))
Extract sf nodes and edges from an osm_graph
Description
Extract sf nodes and edges from an osm_graph
Usage
ox_as_sf(g)
Arguments
g |
An |
Value
A named list with sf elements nodes and edges.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
parts <- ox_as_sf(g)
parts$edges
Convert to an sfnetwork
Description
Returns the graph as a sfnetworks::sfnetwork() object, ready for the
sfnetworks/tidygraph spatial-network workflow.
Usage
ox_as_sfnetwork(g, directed = TRUE)
Arguments
g |
An osm_graph. |
directed |
Build a directed network. Default |
Value
An sfnetwork.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
ox_as_sfnetwork(g)
Convert to a tidygraph table graph
Description
Returns the graph as a tidygraph::tbl_graph(), dropping geometry (node
coordinates are kept as x/y columns).
Usage
ox_as_tidygraph(g, directed = TRUE)
Arguments
g |
An osm_graph. |
directed |
Build a directed graph. Default |
Value
A tbl_graph.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
ox_as_tidygraph(g)
Basic street-network statistics
Description
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.
Usage
ox_basic_stats(g, weight = "length")
Arguments
g |
An osm_graph. |
weight |
Edge column used as length/weight. Default |
Value
A one-row tibble of statistics.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
ox_basic_stats(g)
Compute edge compass bearings
Description
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.
Usage
ox_bearings(g)
Arguments
g |
An osm_graph. |
Value
A numeric vector of bearings, one per edge.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
head(ox_bearings(g))
Blend points or another graph into a street network
Description
Snaps point locations onto their nearest network edge and splits that edge
there, turning each snapped location into a routable node — the osmnxr
counterpart of sfnetworks::st_network_blend(), with the snapping done in
the Rust core (grid-indexed planar distance) so city-sized networks blend
in seconds.
Usage
ox_blend(
g,
y,
tolerance = Inf,
connector_attrs = list(),
snap_nodes = TRUE,
snap_edges = TRUE,
connector_node_attrs = character()
)
Arguments
g |
An osm_graph to blend into. |
y |
What to blend: an |
tolerance |
Maximum snapping distance, in CRS units. Points (or |
connector_attrs |
Named list of constant attribute values for the
connector edges created in graph mode (e.g.
|
snap_nodes |
Which points (or |
snap_edges |
Which edges of |
connector_node_attrs |
Character vector of |
Details
Two-way streets are handled properly: every edge sharing the split edge's
geometry (its reversed twin, or a same-direction duplicate) is split at the
same location into the same new node, so routability is preserved in both
directions. Points that project onto an existing node are attached to that
node instead of splitting. Points farther than tolerance from every edge
are left out with a warning. New nodes get consecutive osmids starting
just above the largest id in sight (g's — and y's too in graph mode),
so existing ids keep their meaning.
When y is another osm_graph, the result is a combined
multimodal network, built in three steps (as proposed in the issue that
motivated this feature): (1) every node of y (within tolerance, and
flagged by snap_nodes) is blended into g as above; (2) the two graphs
are stacked with ox_union(), so y's own nodes and edges are kept
intact; (3) a pair of directed connector edges is added between each y
node and the node it snapped to, which is the connectivity a plain blend +
union would miss. Node osmids shared by both graphs are merged by the
union directly (no connector needed) — but only when they sit at the same
coordinates: reusing an id of g for a genuinely different location in
y is an error (renumber y's ids first). The union here does not
deduplicate edges (the two layers are assumed to be distinct networks);
combine overlapping downloads with ox_union() first when that matters.
Distances are planar, in the units of the graph's CRS (reproject
geographic networks first — sf::st_transform() on nodes and edges —
when a metric tolerance matters). Split edges keep their attributes;
length is
recomputed from the new geometries, and travel_time / penalty (when
present) are rescaled proportionally to each piece's share of the parent
edge, so routing weights stay consistent.
Value
An osm_graph. meta$blend records the mapping as
a tibble: one row per input point (or y node not
shared with g), with the node osmid it became or attached to (NA
when beyond tolerance or flagged off by snap_nodes), the snapping
distance, and u / v — the endpoints of the g edge it snapped onto,
as that edge was before the blend (splitting replaces it with pieces
chained through the new nodes).
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
# blend two POIs into the grid: each becomes a routable node
pts <- sf::st_sfc(sf::st_point(c(150, 40)), sf::st_point(c(250, 260)),
crs = 3857)
b <- ox_blend(g, pts)
b$meta$blend
ox_shortest_path(b, b$meta$blend$node[1], b$meta$blend$node[2])
# blend a tiny second network (e.g. a metro line) into the grid
metro <- new_osm_graph(
sf::st_sf(osmid = c(1001, 1002), access_time = c(30, 45),
geometry = sf::st_sfc(sf::st_point(c(40, 150)),
sf::st_point(c(260, 150)), crs = 3857)),
sf::st_sf(u = 1001, v = 1002, length = 220,
geometry = sf::st_sfc(sf::st_linestring(
rbind(c(40, 150), c(260, 150))), crs = 3857)),
meta = list(network_type = "metro")
)
mm <- ox_blend(g, metro, connector_attrs = list(highway = "connector"),
connector_node_attrs = "access_time")
mm
Node centrality
Description
Computes betweenness and/or closeness centrality for every node, using the Rust core (Brandes' algorithm for betweenness; one Dijkstra per node for closeness).
Usage
ox_centrality(
g,
type = c("betweenness", "closeness"),
weight = "length",
normalized = TRUE
)
Arguments
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 |
Value
A tibble with column osmid plus one column per
requested measure.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph(n = 4)
ox_centrality(g, type = "betweenness")
Average network circuity
Description
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.
Usage
ox_circuity(g)
Arguments
g |
An osm_graph. |
Value
A numeric scalar (>= 1).
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
ox_circuity(g)
Clear the session cache
Description
Empties the in-memory cache of downloaded OpenStreetMap responses, and the
cache of routing edge indexes that makes repeated ox_route_*() /
ox_shortest_path() calls on the same graph fast. Both caches are rebuilt
transparently on demand; clearing them only frees memory.
Usage
ox_clear_cache()
Value
Invisibly NULL.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
ox_clear_cache()
Consolidate nearby intersections
Description
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).
Usage
ox_consolidate_intersections(g, tolerance = 10)
Arguments
g |
An osm_graph. |
tolerance |
Distance below which nodes are merged, in CRS units.
Either one number for the whole graph (default |
Details
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.
Consolidating an already-consolidated graph (meta$consolidated is set)
warns but proceeds, clustering the consolidated nodes again — legitimate
for growing the tolerance, but usually a mistake.
Value
A consolidated osm_graph (with meta$consolidated = TRUE).
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
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)
Shortest-path distance matrix
Description
Computes the matrix of minimum-weight distances between every from node and
every to node (Rust core; one Dijkstra per source).
Usage
ox_distance_matrix(g, from, to = from, weight = "length")
Arguments
g |
An osm_graph. |
from |
Node |
to |
Node |
weight |
Edge column used as weight. Default |
Value
A numeric matrix (length(from) x length(to)) with osmid
dimnames; Inf marks unreachable pairs.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph(n = 3)
nodes <- g$nodes$osmid
ox_distance_matrix(g, from = nodes[1:2], to = nodes[3:4])
Single-source shortest distances
Description
Minimum-weight distance from from to every node in the graph.
Usage
ox_distances(g, from, weight = "length")
Arguments
g |
An osm_graph. |
from |
A node |
weight |
Edge column used as weight. Default |
Value
A tibble with columns osmid and distance
(Inf for unreachable nodes).
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
ox_distances(g, ox_nearest_nodes(g, 0, 0))
Load a bundled real-world example network
Description
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.
Usage
ox_example(name = c("olinda", "manhattan", "rome"))
Arguments
name |
Which network to load (all drivable, simplified):
|
Value
An osm_graph.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- ox_example("olinda")
g
ox_basic_stats(g)
Download features within a bounding box
Description
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).
Usage
ox_features_from_bbox(bbox, tags)
Arguments
bbox |
Numeric |
tags |
Named list of OSM tag filters. Each element is either |
Value
An sf of POINT features with osm_type, osm_id and one column
per tag encountered.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
bbox <- c(-34.91, -8.07, -34.87, -8.04)
ox_features_from_bbox(bbox, tags = list(amenity = "school"))
Download features for a named place
Description
Geocodes query with ox_geocode() and downloads matching features around
it. See ox_features_from_bbox() for the tags format.
Usage
ox_features_from_place(query, tags, dist = 2000)
Arguments
query |
A place name, e.g. |
tags |
Named list of OSM tag filters. |
dist |
Search half-width in metres around the geocoded point. Default
|
Value
An sf of POINT features.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
ox_features_from_place("Olinda, Brazil", tags = list(amenity = "hospital"))
Geocode a place or address
Description
Resolve a free-form query to coordinates and metadata using the OpenStreetMap Nominatim service.
Usage
ox_geocode(query, limit = 1)
Arguments
query |
A character scalar, e.g. |
limit |
Maximum number of results. Default |
Value
A tibble with columns display_name, lat,
lon, osm_type, osm_id and class.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
ox_geocode("Recife, Brazil")
Geocode a place to an sf boundary
Description
Like ox_geocode() but returns the place geometry (boundary polygon when
available, otherwise a point) as an sf object.
Usage
ox_geocode_to_sf(query, limit = 1)
Arguments
query |
A character scalar, e.g. |
limit |
Maximum number of results. Default |
Value
An sf object (one row per result) in EPSG:4326.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
ox_geocode_to_sf("Recife, Brazil")
Download a street network around an address
Description
Download a street network around an address
Usage
ox_graph_from_address(address, dist = 1000, network_type = "drive")
Arguments
address |
A street address. |
dist |
Buffer half-width in metres. Default |
network_type |
One of |
Value
An osm_graph.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- ox_graph_from_address("Marco Zero, Recife", dist = 600)
Download a street network within a bounding box
Description
Download a street network within a bounding box
Usage
ox_graph_from_bbox(bbox, network_type = "drive")
Arguments
bbox |
Numeric vector |
network_type |
One of |
Details
Transient Overpass failures (HTTP 429/5xx, dropped connections) are retried
automatically with exponential backoff; the Overpass endpoint, timeout and
number of attempts are configurable via ox_settings().
Value
An osm_graph.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
bbox <- c(-34.91, -8.07, -34.87, -8.04)
g <- ox_graph_from_bbox(bbox, network_type = "drive")
Download a street network for a named place
Description
Geocodes query with ox_geocode() and downloads the street network within
the bounding box of the matched place.
Usage
ox_graph_from_place(query, network_type = "drive")
Arguments
query |
A place name, e.g. |
network_type |
One of |
Value
An osm_graph.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- ox_graph_from_place("Olinda, Brazil", network_type = "drive")
Download a street network around a point
Description
Download a street network around a point
Usage
ox_graph_from_point(point, dist = 1000, network_type = "drive")
Arguments
point |
Numeric |
dist |
Buffer half-width in metres (a square bounding box of side
|
network_type |
One of |
Value
An osm_graph.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- ox_graph_from_point(c(-34.89, -8.05), dist = 800)
Compute isochrones (service areas)
Description
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.
Usage
ox_isochrone(g, center, cutoffs, weight = "length", ratio = 0.4)
Arguments
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 |
Details
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.
Value
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.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph(n = 6, spacing = 100)
center <- ox_nearest_nodes(g, 250, 250)
iso <- ox_isochrone(g, center, cutoffs = c(100, 300))
iso
k shortest paths between two nodes
Description
Computes up to k loopless shortest paths from from to to using Yen's
algorithm in the Rust core, returning node sequences. See
ox_route_shortest() for the richer sf interface that also returns each
route's street geometry.
Usage
ox_k_shortest_paths(g, from, to, k = 3, weight = "length")
Arguments
g |
An osm_graph. |
from, to |
Node |
k |
Number of paths to return. Default |
weight |
Edge column used as weight. Default |
Value
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.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
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)
Load a graph from GraphML
Description
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).
Usage
ox_load_graphml(path)
Arguments
path |
Path to a |
Value
An osm_graph.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
f <- tempfile(fileext = ".graphml")
ox_save_graphml(g, f)
ox_load_graphml(f)
Find the nearest edge to a point
Description
Returns, for each supplied coordinate, the graph edge closest in planar distance.
Usage
ox_nearest_edges(g, x, y)
Arguments
g |
An osm_graph. |
x, y |
Numeric vectors of coordinates in the graph's CRS. |
Value
An sf subset of g$edges, one row per input point.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
ox_nearest_edges(g, x = 50, y = 0)
Find the nearest node to a point
Description
Returns the osmid of the graph node closest (in planar distance) to each
supplied coordinate.
Usage
ox_nearest_nodes(g, x, y)
Arguments
g |
An osm_graph. |
x, y |
Numeric vectors of coordinates in the graph's CRS. |
Value
An integer/numeric vector of node osmids, one per input point.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
ox_nearest_nodes(g, x = 0, y = 0)
Street-orientation entropy
Description
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.
Usage
ox_orientation_entropy(x, num_bins = 36)
Arguments
x |
An osm_graph or a numeric vector of bearings
(degrees), e.g. from |
num_bins |
Number of equal bearing sectors over |
Value
A numeric scalar (entropy in nats).
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
ox_orientation_entropy(g)
Figure-ground diagram of a street network
Description
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).
Usage
ox_plot_figure_ground(g, bg = "black", col = "white", lwd = 1.2, title = NULL)
Arguments
g |
An osm_graph. |
bg, col |
Background and street colours. Default white-on-black. |
lwd |
Street line width. Default |
title |
Optional panel title. |
Value
Invisibly, the osm_graph.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
ox_plot_figure_ground(g)
Polar plot of street orientations
Description
Draws a polar histogram (rose plot) of edge compass bearings, the standard
visual summary of a street network's orientation order. Requires ggplot2.
Usage
ox_plot_orientation(
x,
num_bins = 36,
fill = "#0d3b66",
title = "Street orientation"
)
Arguments
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. |
Value
A ggplot object.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
ox_plot_orientation(g)
Constrained shortest path
Description
Finds the minimum-weight route from from to to whose total
consumption of a second edge column (resource) does not exceed budget —
e.g. "the shortest route using at most 500 m of residential streets", with
the residential metres counted by ox_add_edge_penalties(). This is the
classic constrained shortest path problem.
Usage
ox_route_constrained(
g,
from,
to,
weight = "length",
resource,
budget,
method = c("exact", "lagrangian")
)
Arguments
g |
An osm_graph. |
from, to |
Node |
weight |
Edge column used as routing cost. Default |
resource |
Name of a nonnegative edge column holding the second
criterion, e.g. the |
budget |
Maximum total resource the route may consume. |
method |
|
Details
Two solvers, both in the Rust core:
-
method = "exact"(default) — bicriteria label-setting; always returns the true optimum (seeox_route_pareto()for the machinery and for the full cost-vs-resource trade-off curve). -
method = "lagrangian"— Lagrangian relaxation (the LARAC algorithm): the budget constraint is dualized, so each iteration is a plain Dijkstra onweight + lambda * resource, with a binary search drivinglambdato the dual optimum. It scales to networks where the exact front grows too large, at the price of a possible duality gap: the route is always feasible, andlower_boundbrackets how far from optimal it can be (cost == lower_boundproves optimality; a message reports any gap).
Value
A one-row sf tibble: cost, resource, lower_bound (a proven
lower bound on the optimal cost; equals cost whenever optimality is
certified, which is always the case for method = "exact"), a
list-column path of the node osmids traversed, and the route's merged
street geometry. An error is raised when no route fits the budget (the
message reports the minimum feasible resource).
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
g$edges$highway <- ifelse(abs(g$edges$u - g$edges$v) == 1, "residential", "primary")
g <- ox_add_edge_penalties(g, c(residential = 1))
from <- ox_nearest_nodes(g, 0, 0)
to <- ox_nearest_nodes(g, 300, 300)
# shortest route crossing at most 300 m of residential streets
ox_route_constrained(g, from, to, resource = "penalty", budget = 300)
ox_route_constrained(g, from, to, resource = "penalty", budget = 300,
method = "lagrangian")
Pareto-optimal routes trading cost against a resource
Description
Enumerates the routes from from to to that are Pareto-optimal in two
criteria: the routing weight (cost) and a second nonnegative edge column
(resource), typically a road-type penalty from ox_add_edge_penalties().
Each returned route is cheaper than the next and uses more resource than
the next; no other route is better on both criteria. The front is computed
exactly in the Rust core by bicriteria label-setting (Martins' algorithm)
with dominance pruning and reverse-Dijkstra bounds.
Usage
ox_route_pareto(
g,
from,
to,
weight = "length",
resource,
budget = Inf,
max_routes = Inf
)
Arguments
g |
An osm_graph. |
from, to |
Node |
weight |
Edge column used as routing cost. Default |
resource |
Name of a nonnegative edge column holding the second
criterion, e.g. the |
budget |
Keep only routes with total resource at most |
max_routes |
Return at most this many routes (the cheapest ones).
Default |
Details
With a finite budget the front is restricted to routes whose total
resource is at most budget; its first row is then the exact solution of
the constrained shortest path problem (see ox_route_constrained()).
The bicriteria problem is NP-hard in general — the front can be large on
pathological inputs — but on street networks with sparse penalties the
pruned search is fast. Use max_routes to cap the enumeration.
Value
An sf tibble with one row per Pareto-optimal route, ordered by
increasing cost (and decreasing resource): route (rank), cost,
resource, a list-column path of the node osmids traversed, and the
route's merged street geometry.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
# north-south streets are calm residential, east-west ones primary
g$edges$highway <- ifelse(abs(g$edges$u - g$edges$v) == 1, "residential", "primary")
g <- ox_add_edge_penalties(g, c(residential = 1))
from <- ox_nearest_nodes(g, 0, 0)
to <- ox_nearest_nodes(g, 300, 300)
ox_route_pareto(g, from, to, resource = "penalty")
Shortest route(s) between two nodes, with geometry
Description
The sf routing interface, uniform with the rest of the ox_route_*
family: computes the minimum-weight route from from to to (Dijkstra,
in the Rust core) and returns it with its cost and merged street geometry.
With k > 1 it returns up to k loopless route alternatives (Yen's
algorithm), one per row, ordered by increasing cost.
Usage
ox_route_shortest(g, from, to, weight = "length", k = 1)
Arguments
g |
An osm_graph. |
from, to |
Node |
weight |
Edge column used as weight. Default |
k |
Number of route alternatives to return. Default |
Details
The geometry is built from the edges the solver actually traversed, so it
is exact across parallel edges. ox_shortest_path() and
ox_k_shortest_paths() remain as the lighter variants returning only node
sequences.
Value
An sf tibble with one row per route: route (rank), cost, a
list-column path of the node osmids traversed, and the route's merged
street geometry. An error is raised when to is unreachable from from.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
from <- ox_nearest_nodes(g, 0, 0)
to <- ox_nearest_nodes(g, 300, 300)
ox_route_shortest(g, from, to)
ox_route_shortest(g, from, to, k = 3)
Travelling-salesman route through a set of nodes
Description
Finds a short route through nodes over the street network, in the spirit
of sfnetworks::st_network_travel(). Network distances between all pairs of
stops are computed in the Rust core (one Dijkstra per stop, so one-way
streets are respected via the asymmetric cost matrix), the visiting order is
solved with an iterated local search, and each leg is expanded back into a
shortest path with its street geometry.
Usage
ox_route_tsp(
g,
nodes,
weight = "length",
start = 1,
end = start,
method = c("ils", "nn")
)
Arguments
g |
An osm_graph. |
nodes |
Node |
weight |
Edge column used as weight. Default |
start |
Index into |
end |
Index into |
method |
|
Details
The default solver builds a nearest-neighbour tour and polishes it with an
iterated local search: a descent over or-opt (segment relocation), swap and
2-opt moves — every move evaluated exactly on the asymmetric cost matrix —
restarted from double-bridge perturbations, keeping the best tour found.
The search is deterministic (an internal fixed-seed RNG drives the
perturbations, leaving R's RNG untouched). It routinely finds the global
optimum for small stop counts, but optimality is not guaranteed (the TSP is
NP-hard). method = "nn" skips the improvement and keeps the raw
nearest-neighbour order.
Value
An sf tibble with one row per leg of the route: leg, from and
to (node osmids), cost (network distance in weight units), a
list-column path of the osmids traversed, and the leg's LINESTRING
geometry. The total route cost is sum(out$cost).
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
stops <- c(1, 4, 13, 16, 6)
route <- ox_route_tsp(g, stops)
route
sum(route$cost)
Save a graph to GraphML
Description
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().
Usage
ox_save_graphml(g, path)
Arguments
g |
An osm_graph. |
path |
Output |
Value
path, invisibly.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
f <- tempfile(fileext = ".graphml")
ox_save_graphml(g, f)
Get or set package settings
Description
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.
Usage
ox_settings(...)
Arguments
... |
Named settings to update. Recognised names: |
Details
timeout (seconds) applies both to the HTTP request and to the Overpass
server-side query timeout. max_tries is the total number of attempts per
request: transient failures — HTTP 429, 500, 502, 503, 504 and dropped
connections, which busy Overpass/Nominatim servers routinely return — are
retried with exponential backoff (honouring any Retry-After header)
before an error is raised. cache toggles the in-session response cache
(see ox_clear_cache()).
Value
A named list of settings (current values, or the previous values invisibly when updating).
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
ox_settings()
old <- ox_settings(timeout = 300)
ox_settings(timeout = old$timeout) # restore
Shortest path between two nodes
Description
Computes the minimum-weight path from from to to using Dijkstra's
algorithm in the Rust core, returning just the node sequence. See
ox_route_shortest() for the richer sf interface that also returns the
route's cost and street geometry (and alternatives via k).
Usage
ox_shortest_path(g, from, to, weight = "length")
Arguments
g |
An osm_graph. |
from, to |
Node |
weight |
Edge column used as weight. Default |
Value
A vector of node osmids describing the path (length 0 if the
target is unreachable).
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
from <- ox_nearest_nodes(g, 0, 0)
to <- ox_nearest_nodes(g, 300, 300)
ox_shortest_path(g, from, to)
Simplify street-network topology
Description
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.
Usage
ox_simplify(g, edge_attr_aggs = NULL)
Arguments
g |
An unsimplified osm_graph. |
edge_attr_aggs |
Named list of functions combining the per-segment
values of an edge attribute along each merged chain, e.g.
|
Details
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.
Every edge attribute column survives simplification: a merged edge takes
the value of its first segment, except for columns named in
edge_attr_aggs, whose per-segment values are combined by the given
function (as in OSMnx 2). length is always recomputed from the merged
geometry unless an explicit length aggregator is supplied, and
n_segments records how many segments each edge merged.
Value
A simplified osm_graph (with meta$simplified = TRUE).
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
ox_simplify(g) # already simplified: returned unchanged
Export to GeoJSON
Description
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.
Usage
ox_to_geojson(g, path, layer = c("edges", "nodes"))
Arguments
g |
An osm_graph. |
path |
Output file path. |
layer |
Which layer to write: |
Value
path, invisibly.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
ox_to_geojson(g, tempfile(fileext = ".geojson"))
Build a MapLibre GL style fragment
Description
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).
Usage
ox_to_maplibre(
g,
path,
source_id = "osmnxr",
layer_id = "streets",
url = basename(path)
)
Arguments
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
|
Value
A named list with sources and layers, invisibly written data to
path.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
style <- ox_to_maplibre(g, tempfile(fileext = ".geojson"))
names(style)
Union of osm_graph objects
Description
Combines two or more graphs into a single osm_graph. Node
and edge tables are stacked; nodes sharing an osmid are merged (the first
occurrence wins) and edges duplicated across graphs are dropped. Attribute
columns present in one graph but not another are filled with NA.
Usage
ox_union(..., dedupe_edges = TRUE)
Arguments
... |
Two or more |
dedupe_edges |
Drop edges that appear in more than one graph with
identical |
Details
Nodes with the same osmid are treated as the same location, which is what
stitches the graphs together: overlapping downloads share their OSM node
ids, and a hand-built network (say, a metro layer) connects to a street
graph wherever its edges reference street-node osmids. Custom networks
should therefore use node ids that do not collide with OSM's except where a
connection is intended (negative ids are a safe choice).
Value
An osm_graph. meta$network_type concatenates the
distinct input types (e.g. "drive+walk"), meta$simplified is TRUE
only if every input was simplified, and meta$union_of records how many
graphs were combined.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g1 <- example_osm_graph(n = 3)
# a second, disjoint network with its own node ids
g2 <- example_osm_graph(n = 3)
g2$nodes$osmid <- g2$nodes$osmid + 1000
g2$edges$u <- g2$edges$u + 1000
g2$edges$v <- g2$edges$v + 1000
u <- ox_union(g1, g2)
u
# unioning overlapping graphs dedupes shared nodes and edges
nrow(ox_union(g1, g1)$edges) == nrow(g1$edges)
Validate an osm_graph
Description
Checks that a graph meets the structural expectations the rest of the
package relies on, and fails with one actionable bullet per problem found
(all problems are collected first, so one run shows everything). Useful
after assembling a graph by hand — a metro layer for ox_blend(), say —
or after editing nodes/edges directly.
Usage
ox_validate(g, tolerance = 1e-06)
Arguments
g |
An osm_graph. |
tolerance |
Maximum distance, in CRS units, between an edge geometry
endpoint and its |
Details
The checks: nodes and edges are sf with POINT / LINESTRING
geometries and no empty geometries, sharing one CRS; nodes$osmid exists,
is numeric, complete and unique; edges$u/edges$v exist, are complete,
and reference existing node osmids; edges$length exists, is numeric,
complete and nonnegative; and each edge's geometry starts at its u node
and ends at its v node (within tolerance, in CRS units) — the
invariant that keeps routing results and drawn geometry in agreement.
Value
g, invisibly, when the graph is valid; otherwise an error
listing every problem found.
References
osmnxr is an R port of OSMnx. If you use it, please cite:
Boeing, G. (2025). Modeling and analyzing urban networks and amenities with OSMnx. Geographical Analysis, 57(4), 567–577. doi:10.1111/gean.70009
Examples
g <- example_osm_graph()
ox_validate(g)
Plot an osm_graph
Description
Draws the street-network edges (and optionally nodes) using base sf
plotting.
Usage
## S3 method for class 'osm_graph'
plot(x, nodes = FALSE, col = "#0d3b66", lwd = 0.7, ...)
Arguments
x |
An |
nodes |
Logical; overlay node points. Default |
col, lwd |
Passed to the edge geometry plot. |
... |
Further arguments passed to |
Value
Invisibly, the osm_graph.
Basic network statistics from edge endpoints (0-based) and weights.
Description
Basic network statistics from edge endpoints (0-based) and weights.
Usage
rs_basic_stats(from, to, weight, n_nodes)
Initial compass bearings (degrees) for parallel coordinate vectors.
Description
Initial compass bearings (degrees) for parallel coordinate vectors.
Usage
rs_bearings(lat1, lon1, lat2, lon2)
Betweenness centrality (Brandes) for every node.
Description
Betweenness centrality (Brandes) for every node.
Usage
rs_betweenness(from, to, weight, n_nodes, normalized)
Closeness centrality for every node.
Description
Closeness centrality for every node.
Usage
rs_closeness(from, to, weight, n_nodes, normalized)
Connected-component label (0-based root index) for each node, given
undirected a–b adjacency pairs.
Description
Connected-component label (0-based root index) for each node, given
undirected a–b adjacency pairs.
Usage
rs_connected_components(a, b, n_nodes)
Constrained shortest path by Lagrangian relaxation (LARAC): each
iteration is a plain Dijkstra on cost + lambda * resource, with a
binary search driving lambda to the dual optimum. Returns a list with
found; when TRUE also path (0-based nodes), edges (0-based
input-order indices of the traversed edges), cost, resource,
lower_bound (dual bound on the optimal cost; equal to cost proves
optimality), lambda and iterations (Dijkstra runs).
Description
Constrained shortest path by Lagrangian relaxation (LARAC): each
iteration is a plain Dijkstra on cost + lambda * resource, with a
binary search driving lambda to the dual optimum. Returns a list with
found; when TRUE also path (0-based nodes), edges (0-based
input-order indices of the traversed edges), cost, resource,
lower_bound (dual bound on the optimal cost; equal to cost proves
optimality), lambda and iterations (Dijkstra runs).
Usage
rs_csp_lagrangian(
from,
to,
w_cost,
w_resource,
n_nodes,
source,
target,
budget,
max_iter
)
Single-source shortest distances (length n_nodes); Inf if unreachable.
Description
Single-source shortest distances (length n_nodes); Inf if unreachable.
Usage
rs_dijkstra(from, to, weight, n_nodes, source)
Row-major shortest-distance matrix from each source to each target
(0-based indices). Length is sources * targets.
Description
Row-major shortest-distance matrix from each source to each target
(0-based indices). Length is sources * targets.
Usage
rs_distance_matrix(from, to, weight, n_nodes, sources, targets)
Yen's k loopless shortest paths. Returns a list with paths (a list of
0-based node-index vectors), edge_paths (0-based input-order indices of
the edges traversed — the minimum-weight edge of each consecutive node
pair, matching Yen's simple-graph abstraction) and costs (numeric).
Description
Yen's k loopless shortest paths. Returns a list with paths (a list of
0-based node-index vectors), edge_paths (0-based input-order indices of
the edges traversed — the minimum-weight edge of each consecutive node
pair, matching Yen's simple-graph abstraction) and costs (numeric).
Usage
rs_k_shortest_paths(from, to, weight, n_nodes, source, target, k)
Shannon entropy of binned edge bearings (degrees).
Description
Shannon entropy of binned edge bearings (degrees).
Usage
rs_orientation_entropy(bearings, num_bins)
Bicriteria shortest paths (Pareto front) from source to target by
label-setting with dominance pruning. Each edge carries a cost and a
resource weight; budget caps the path resource (Inf for none) and
max_routes <= 0 returns the whole front. Returns a list with paths
(0-based node-index vectors), edge_paths (0-based indices of the edges
actually traversed, in input order), costs and resources, ordered by
increasing cost.
Description
Bicriteria shortest paths (Pareto front) from source to target by
label-setting with dominance pruning. Each edge carries a cost and a
resource weight; budget caps the path resource (Inf for none) and
max_routes <= 0 returns the whole front. Returns a list with paths
(0-based node-index vectors), edge_paths (0-based indices of the edges
actually traversed, in input order), costs and resources, ordered by
increasing cost.
Usage
rs_pareto_paths(
from,
to,
w_cost,
w_resource,
n_nodes,
source,
target,
budget,
max_routes
)
Shortest path between source and target. Returns a list with path
(0-based node indices), edges (0-based input-order indices of the edges
actually traversed, parallel edges included) and cost; path is empty
and cost is Inf when the target is unreachable.
Description
Shortest path between source and target. Returns a list with path
(0-based node indices), edges (0-based input-order indices of the edges
actually traversed, parallel edges included) and cost; path is empty
and cost is Inf when the target is unreachable.
Usage
rs_shortest_path(from, to, weight, n_nodes, source, target)
Simplified node chains between topological endpoints. Returns a list of 0-based node-index vectors, one per merged edge.
Description
Simplified node chains between topological endpoints. Returns a list of 0-based node-index vectors, one per merged edge.
Usage
rs_simplify_paths(from, to, n_nodes)
Snap points to the nearest edge polyline (planar distance, grid-indexed).
Edges arrive as flattened vertex coordinates (vx/vy) plus 0-based
per-edge offsets (length n_edges + 1). Returns a list with, per point:
edge (0-based nearest edge, -1 when none within tolerance), dist,
the snapped coordinates x/y, and pos (planar distance along the
edge's polyline from its first vertex).
Description
Snap points to the nearest edge polyline (planar distance, grid-indexed).
Edges arrive as flattened vertex coordinates (vx/vy) plus 0-based
per-edge offsets (length n_edges + 1). Returns a list with, per point:
edge (0-based nearest edge, -1 when none within tolerance), dist,
the snapped coordinates x/y, and pos (planar distance along the
edge's polyline from its first vertex).
Usage
rs_snap_points(vx, vy, offsets, px, py, tolerance)
Heuristic travelling-salesman visiting order over a row-major n x n
cost matrix (nearest-neighbour construction, or-opt improvement when
improve). The tour starts at start (0-based); closed = TRUE returns
there, otherwise end >= 0 pins the final stop and end = -1 leaves it
free. Returns 0-based indices into the matrix.
Description
Heuristic travelling-salesman visiting order over a row-major n x n
cost matrix (nearest-neighbour construction, or-opt improvement when
improve). The tour starts at start (0-based); closed = TRUE returns
there, otherwise end >= 0 pins the final stop and end = -1 leaves it
free. Returns 0-based indices into the matrix.
Usage
rs_tsp_tour(cost, n, start, end, closed, improve)