### Install Pre-commit Hooks Source: https://github.com/gboeing/osmnx/blob/main/tests/README.md Install pre-commit hooks to automatically format code according to project standards before committing. Run this command from the repository root. ```shell pre-commit install ``` -------------------------------- ### Install OSMnx with Pip Source: https://github.com/gboeing/osmnx/blob/main/docs/source/installation.md Installs OSMnx using pip into a virtual environment. This method may require manual compilation of dependencies if precompiled binaries are not available. ```shell pip install osmnx ``` -------------------------------- ### _open_file(filepath, encoding) Source: https://github.com/gboeing/osmnx/blob/main/docs/source/internals-reference.md Open a file and return a file object, optionally handling bz2 or gz files. Uses a wrapper context manager to ensure the file will always get closed. ```APIDOC ## osmnx._osm_xml._open_file(filepath, encoding) ### Description Open a file and return a file object, optionally handling bz2 or gz files. Uses a wrapper context manager to yield the file object to ensure the file will always get closed when the caller is finished with it. ### Parameters * **filepath** (*Path*) - Path to file. * **encoding** (*str*) - The file’s character encoding. ### Returns *file* - The file handle. ### Return type Iterator[TextIO] ``` -------------------------------- ### Install OSMnx with Conda Source: https://github.com/gboeing/osmnx/blob/main/docs/source/installation.md Creates a new conda environment named 'ox' and installs OSMnx from the conda-forge channel. Add other package names after 'osmnx' to install them in the same environment. ```shell conda create --strict-channel-priority -c conda-forge -n ox osmnx ``` -------------------------------- ### startElement(name, attrs) Source: https://github.com/gboeing/osmnx/blob/main/docs/source/internals-reference.md Signals the start of an element in non-namespace mode. The name parameter contains the raw XML 1.0 name of the element type and the attrs parameter holds an instance of the Attributes class. ```APIDOC ## startElement(name, attrs) ### Description Signals the start of an element in non-namespace mode. The name parameter contains the raw XML 1.0 name of the element type and the attrs parameter holds an instance of the Attributes class containing the attributes of the element. ### Parameters * **name** (*str*) - The raw XML 1.0 name of the element type. * **attrs** (*AttributesImpl*) - An instance of the Attributes class containing the attributes of the element. ### Return type None ``` -------------------------------- ### osmnx.plot._verify_mpl Source: https://github.com/gboeing/osmnx/blob/main/docs/source/internals-reference.md Verifies that the matplotlib library is installed and has been imported. This is a utility function to ensure plotting dependencies are met. ```APIDOC ## osmnx.plot._verify_mpl() ### Description Verify that matplotlib is installed and imported. ### Returns *None* ### Return type None ``` -------------------------------- ### Run All Pre-commit Hooks Source: https://github.com/gboeing/osmnx/blob/main/tests/README.md Apply all pre-commit hooks to the entire project to ensure consistent code formatting and style. Execute this command from the repository root. ```shell pre-commit run -a ``` -------------------------------- ### Sync Dependencies and Run Lint Test Source: https://github.com/gboeing/osmnx/blob/main/tests/README.md Synchronize development dependencies and execute the linting test script. Run these commands from the repository root. ```shell uv sync --all-extras --all-groups ``` ```shell bash ./tests/lint_test.sh ``` -------------------------------- ### Consolidate Intersections in OSMnx Graph Source: https://context7.com/gboeing/osmnx/llms.txt Consolidates nearby nodes representing the same physical intersection into a single node. Can be used to rebuild the graph or just get a GeoDataFrame of consolidated nodes. ```python import osmnx as ox G = ox.graph.graph_from_place("Piedmont, California", network_type="drive") G_proj = ox.projection.project_graph(G) # Consolidate nodes within 15 m of each other G_consolidated = ox.simplification.consolidate_intersections(G_proj, tolerance=15) print(f"Before: {len(G_proj)} nodes") print(f"After: {len(G_consolidated)} nodes") # Just get consolidated node GeoDataFrame without rebuilding the graph gdf_consolidated = ox.simplification.consolidate_intersections( G_proj, tolerance=15, rebuild_graph=False, dead_ends=False ) ``` -------------------------------- ### _nominatim_request Source: https://github.com/gboeing/osmnx/blob/main/docs/source/internals-reference.md Sends an HTTP GET request to the Nominatim API with specified parameters and returns the JSON response. Supports different request types like 'search', 'reverse', and 'lookup'. ```APIDOC ### _nominatim_request Send a HTTP GET request to the Nominatim API and return response. ### Parameters * **params** (*OrderedDict* *[**str* *,* *int* *|* *str* *]*) – Key-value pairs of parameters. * **request_type** (*str*) – Which Nominatim API endpoint to query, one of {“search”, “reverse”, “lookup”}. ### Returns *response_json* – The Nominatim API’s response. ### Return type list[dict[str, *Any*]] ``` -------------------------------- ### Create Graph from Local OSM XML File Source: https://context7.com/gboeing/osmnx/llms.txt Creates a graph directly from a locally downloaded OSM XML file. Parameters like `bidirectional`, `simplify`, and `retain_all` control graph construction. ```python import osmnx as ox G = ox.graph.graph_from_xml( "my_area.osm", bidirectional=False, simplify=True, retain_all=False, ) print(f"Loaded graph: {len(G)} nodes, {len(G.edges)} edges") ``` -------------------------------- ### routing.k_shortest_paths Source: https://context7.com/gboeing/osmnx/llms.txt Yields the k shortest simple paths using Yen's algorithm. ```APIDOC ## `routing.k_shortest_paths` ### Description Yields the k shortest simple paths using Yen's algorithm. ### Method `osmnx.routing.k_shortest_paths(G, orig, dest, k=1, weight='length')` ### Parameters - **G** (networkx.MultiDiGraph) - The graph to find the k shortest paths in. - **orig** (int) - The origin node ID. - **dest** (int) - The destination node ID. - **k** (int) - The number of shortest paths to yield. Defaults to 1. - **weight** (str) - The edge attribute to use as the weight for shortest path calculation (e.g., 'length', 'travel_time'). Defaults to 'length'. ### Request Example ```python import osmnx as ox G = ox.graph.graph_from_place("Piedmont, California", network_type="drive") orig = ox.distance.nearest_nodes(G, X=-122.2208, Y=37.8240) dest = ox.distance.nearest_nodes(G, X=-122.2050, Y=37.8120) paths = list(ox.routing.k_shortest_paths(G, orig, dest, k=3, weight="length")) for i, p in enumerate(paths): print(f"Path {i+1}: {len(p)} nodes") ``` ### Response - **paths** (generator) - A generator yielding lists of node IDs, each representing one of the k shortest paths. ``` -------------------------------- ### Get OSM Features by Place Source: https://context7.com/gboeing/osmnx/llms.txt Retrieve OSM features within a specified place boundary, filtered by OSM tags. Useful for gathering amenities, buildings, or other features in a defined area. ```python import osmnx as ox # All cafes and restaurants in Vienna gdf = ox.features.features_from_place( "Vienna, Austria", tags={"amenity": ["cafe", "restaurant"]}, ) print(gdf.shape) # (N, M) — rows = features, cols = OSM tag keys print(gdf.index.names) # ['element', 'id'] print(gdf[["name", "amenity", "geometry"]].head(3)) ``` ```python # Building footprints buildings = ox.features.features_from_place( "Paris, France", tags={"building": True}, ) print(buildings.geom_type.value_counts()) ``` -------------------------------- ### Download Bike Network for Multiple Places Source: https://context7.com/gboeing/osmnx/llms.txt Downloads and models a bike network for multiple specified places, returning a single merged graph. `retain_all` controls whether to keep all nodes or only those in the largest connected component. ```python # Multiple places at once (returns a single merged graph) G_multi = ox.graph.graph_from_place( ["Berkeley, California", "Oakland, California"], network_type="bike", retain_all=False, ) ``` -------------------------------- ### Get OSM Features by Bounding Box Source: https://context7.com/gboeing/osmnx/llms.txt Retrieve OSM features within a rectangular bounding box defined by latitude and longitude coordinates. Useful for fetching data in a specific geographic extent. ```python import osmnx as ox gdf = ox.features.features_from_bbox( bbox=(-0.135, 51.490, -0.100, 51.515), # central London tags={"public_transport": True, "highway": "bus_stop"}, ) print(f"Found {len(gdf)} transit features") ``` -------------------------------- ### osmnx.graph.graph_from_bbox Source: https://context7.com/gboeing/osmnx/llms.txt Downloads a network clipped to a bounding box specified as (left, bottom, right, top) in WGS84 decimal degrees. ```APIDOC ## graph_from_bbox ### Description Downloads a network clipped to a bounding box specified as (left, bottom, right, top) in WGS84 decimal degrees. ### Method `osmnx.graph.graph_from_bbox(north, south, east, west, network_type='drive', simplify=True, retain_all=False, truncate_by_edge=True, custom_filter=None, infrastructure=None, buffer_dist=None, timeout=180, save_graph=False, filepath=None, file_format='graphml', encoding='utf-8', log_console=False, use_cache=True, consolidate_intersections=True) ### Parameters * **north** (float) - The northern latitude boundary. * **south** (float) - The southern latitude boundary. * **east** (float) - The eastern longitude boundary. * **west** (float) - The western longitude boundary. * **network_type** (str) - The type of network to download (e.g., 'drive', 'walk', 'bike'). * **simplify** (bool) - Whether to simplify the graph topology. * **retain_all** (bool) - Whether to retain all disconnected components of the graph. * **truncate_by_edge** (bool) - Whether to truncate edges that cross the boundary. * **custom_filter** (str) - An optional custom filter for the Overpass API query. * **infrastructure** (str or list) - Optional OSM tags to filter network elements by infrastructure type. * **buffer_dist** (float) - Optional buffer distance in meters to expand the boundary. * **timeout** (int) - Timeout in seconds for the Overpass API request. * **save_graph** (bool) - Whether to save the downloaded graph to a file. * **filepath** (str) - The path to save the graph file. * **file_format** (str) - The format to save the graph file. * **encoding** (str) - The encoding to use when saving the graph file. * **log_console** (bool) - Whether to print console logs. * **use_cache** (bool) - Whether to use the cache for downloaded data. * **consolidate_intersections** (bool) - Whether to consolidate intersections. ### Request Example ```python import osmnx as ox # Downtown Los Angeles bounding box bbox = (-118.2614, 34.0400, -118.2400, 34.0560) G = ox.graph.graph_from_bbox( bbox[3], bbox[1], bbox[2], bbox[0], # north, south, east, west network_type="drive", simplify=True, truncate_by_edge=True, # keep nodes whose edges cross the boundary ) # Custom Overpass filter for motorway/trunk only G_hw = ox.graph.graph_from_bbox( bbox[3], bbox[1], bbox[2], bbox[0], custom_filter='["highway"~"motorway|trunk"]', network_type="drive", ) ``` ### Response * **G** (networkx.MultiDiGraph) - The downloaded street network as a NetworkX MultiDiGraph object. ``` -------------------------------- ### Get OSM Features by Point Source: https://context7.com/gboeing/osmnx/llms.txt Fetch OSM features within a circular area defined by a center point and a distance in meters. Ideal for localized data retrieval around a specific location. ```python import osmnx as ox # Parks and green spaces near the Eiffel Tower gdf = ox.features.features_from_point( center_point=(48.8584, 2.2945), tags={"leisure": "park", "landuse": "grass"}, dist=1000, ) print(gdf[["name", "leisure", "landuse"]].dropna(how="all").head()) ``` -------------------------------- ### Tag Repository for Release Source: https://github.com/gboeing/osmnx/blob/main/tests/README.md Create a Git tag for a new semantic version to trigger the release process. Replace 'v1.2.3' with the actual version number. ```shell git tag -a "v1.2.3" -m "v1.2.3" ``` -------------------------------- ### osmnx.routing.k_shortest_paths Source: https://github.com/gboeing/osmnx/blob/main/docs/source/user-reference.md Solves for k-shortest paths between an origin and destination node in a graph using Yen's algorithm. It yields each path sequentially. ```APIDOC ## osmnx.routing.k_shortest_paths Solve k shortest paths from an origin node to a destination node. Uses Yen’s algorithm. See also shortest_path to solve just the one shortest path. ### Parameters * **G** (*networkx.MultiDiGraph*) – Input graph. * **orig** (*int*) – Origin node ID. * **dest** (*int*) – Destination node ID. * **k** (*int*) – Number of shortest paths to solve. * **weight** (*str*) – Edge attribute to minimize when solving shortest paths. ### Yields *path* – The node IDs constituting the next-shortest path. ### Return type *Iterator*[list[int]] ``` -------------------------------- ### osmnx.graph.graph_from_xml Source: https://context7.com/gboeing/osmnx/llms.txt Creates a graph directly from a locally downloaded OSM XML (.osm / .osm.bz2) file. ```APIDOC ## graph_from_xml ### Description Creates a graph directly from a locally downloaded OSM XML (`.osm` / `.osm.bz2`) file. ### Method `osmnx.graph.graph_from_xml(filepath, filepath_type='osm', bidirectional=False, simplify=True, retain_all=False, custom_filter=None, infrastructure=None, consolidate_intersections=True, log_console=False) ### Parameters * **filepath** (str) - The path to the OSM XML file. * **filepath_type** (str) - The type of the file ('osm' or 'pbf'). * **bidirectional** (bool) - Whether to create bidirectional edges for one-way streets. * **simplify** (bool) - Whether to simplify the graph topology. * **retain_all** (bool) - Whether to retain all disconnected components of the graph. * **custom_filter** (str) - An optional custom filter for the Overpass API query. * **infrastructure** (str or list) - Optional OSM tags to filter network elements by infrastructure type. * **consolidate_intersections** (bool) - Whether to consolidate intersections. * **log_console** (bool) - Whether to print console logs. ### Request Example ```python import osmnx as ox G = ox.graph.graph_from_xml( "my_area.osm", bidirectional=False, simplify=True, retain_all=False, ) ``` ### Response * **G** (networkx.MultiDiGraph) - The loaded street network as a NetworkX MultiDiGraph object. ``` -------------------------------- ### OSMnx Settings Source: https://context7.com/gboeing/osmnx/llms.txt Global configuration for caching, API endpoints, timeouts, and tag filters. All settings are module-level attributes that can be set at runtime. ```APIDOC ## `osmnx.settings` module Global configuration for caching, API endpoints, timeouts, and tag filters. All settings are module-level attributes that can be set at runtime. ### Key Settings: - `use_cache` (bool): Enable or disable HTTP caching. - `cache_folder` (str): Path to the cache folder. - `http_referer` (str): Custom HTTP referer header. - `overpass_url` (str): Custom Overpass API endpoint. - `overpass_rate_limit` (bool): Whether to enforce Overpass API rate limiting. - `overpass_settings` (str): Custom Overpass API settings string. - `useful_tags_node` (list): List of OSM tags to use for nodes. - `useful_tags_way` (list): List of OSM tags to use for ways. ``` -------------------------------- ### osmnx.utils_geo.bbox_from_point Source: https://github.com/gboeing/osmnx/blob/main/docs/source/user-reference.md Creates a bounding box around a given (lat, lon) point at a specified distance, with options for UTM projection and returning the CRS. ```APIDOC ## osmnx.utils_geo.bbox_from_point(point: tuple[float, float], dist: float, project_utm: bool = False, return_crs: bool = False) -> tuple[float, float, float, float] | tuple[tuple[float, float, float, float], Any] ### Description Create a bounding box around a (lat, lon) point. Create a bounding box some distance (in meters) in each direction (top, bottom, right, and left) from the center point and optionally project it. ### Parameters * **point** (*tuple* *[**float* *,* *float* *]*) – The (lat, lon) center point to create the bounding box around. * **dist** (*float*) – Bounding box distance in meters from the center point. * **project_utm** (*bool*) – If True, return bounding box as UTM-projected coordinates. * **return_crs** (*bool*) – If True, and project_utm is True, then return the projected CRS too. ### Returns *bbox or bbox, crs* – (left, bottom, right, top) or ((left, bottom, right, top), crs). ### Return type tuple[float, float, float, float] | tuple[tuple[float, float, float, float], *Any*] ``` -------------------------------- ### osmnx.utils._get_logger Source: https://github.com/gboeing/osmnx/blob/main/docs/source/internals-reference.md Creates a logger instance or returns an existing one. ```APIDOC ## osmnx.utils._get_logger(name, filename) ### Description Create a logger or return the current one if already instantiated. ### Parameters * **name** (*str*) – Name of the logger. * **filename** (*str*) – Name of the log file, without file extension. ### Returns *logger* – The logger. ### Return type *Logger* ``` -------------------------------- ### Configure OSMnx Settings for Caching and API Source: https://context7.com/gboeing/osmnx/llms.txt Configures global settings for caching, API endpoints, timeouts, and tag filters. Settings are module-level attributes that can be set at runtime. ```python import osmnx as ox # Configure HTTP caching ox.settings.use_cache = True ox.settings.cache_folder = "./osmnx_cache" # Set custom user-agent and Overpass endpoint ox.settings.http_referer = "myresearchproject" ox.settings.overpass_url = "https://overpass-api.de/api/interpreter" ox.settings.overpass_rate_limit = True ox.settings.overpass_settings = "[out:json][timeout:90][maxsize:2073741824]" # Tag filters — control which OSM tags are added as graph attributes ox.settings.useful_tags_node = ["ref", "highway", "traffic_signals"] ox.settings.useful_tags_way = ["bridge", "tunnel", "oneway", "lanes", "highway", "maxspeed", "name", "access"] # Query historical OSM snapshot as of a date ox.settings.overpass_settings = '[out:json][timeout:90][date:"2023-01-01T00:00:00Z"]' G_historical = ox.graph.graph_from_place("Piedmont, California", network_type="drive") ``` -------------------------------- ### Download Motorway/Trunk Network with Custom Filter Source: https://context7.com/gboeing/osmnx/llms.txt Downloads a drive network within a bounding box using a custom Overpass filter to include only motorways and trunks. This allows for specific network type selection beyond standard options. ```python # Custom Overpass filter for motorway/trunk only G_hw = ox.graph.graph_from_bbox( bbox, custom_filter='["highway"~"motorway|trunk"]', network_type="drive", ) ``` -------------------------------- ### Download Walk Network within Bounding Box Source: https://context7.com/gboeing/osmnx/llms.txt Downloads a walk network within a specified distance of a lat/lon coordinate using bounding-box mode. Ensure the coordinate is valid and the distance is appropriate for the desired area. ```python import osmnx as ox center = (37.7749, -122.4194) # San Francisco City Hall # Bounding-box mode: all nodes within a 500 m square G_bbox = ox.graph.graph_from_point(center, dist=500, dist_type="bbox", network_type="walk") ``` -------------------------------- ### osmnx.plot._save_and_show Source: https://github.com/gboeing/osmnx/blob/main/docs/source/internals-reference.md Saves a figure to disk and/or shows it based on the provided arguments. It handles saving the figure to a specified filepath and optionally displaying it. ```APIDOC ## osmnx.plot._save_and_show(fig, ax, show=True, close=True, save=False, filepath=None, dpi=300) ### Description Save a figure to disk and/or show it, as specified by arguments. ### Parameters * **fig** (*matplotlib.figure.Figure*) – The figure. * **ax** (*matplotlib.axes._axes.Axes*) – The axes instance. * **show** (*bool*) – If True, call pyplot.show() to show the figure. * **close** (*bool*) – If True, call pyplot.close() to close the figure. * **save** (*bool*) – If True, save the figure to disk at filepath. * **filepath** (*str* *|* *Path* *|* *None*) – The path to the file if save is True. File format is determined from the extension. If None, save at settings.imgs_folder/image.png. * **dpi** (*int*) – The resolution of saved file if save is True. ### Returns *fig, ax* – The matplotlib figure and axes objects. ### Return type tuple[matplotlib.figure.Figure, matplotlib.axes._axes.Axes] ``` -------------------------------- ### bbox_from_point Source: https://github.com/gboeing/osmnx/blob/main/docs/source/internals-reference.md Creates a bounding box around a given latitude/longitude point at a specified distance in meters. Optionally projects the bounding box to UTM coordinates and returns the CRS. ```APIDOC ## bbox_from_point ### Description Create a bounding box around a (lat, lon) point. Create a bounding box some distance (in meters) in each direction (top, bottom, right, and left) from the center point and optionally project it. ### Parameters * **point** (*tuple* *[**float* *,* *float* *]*) – The (lat, lon) center point to create the bounding box around. * **dist** (*float*) – Bounding box distance in meters from the center point. * **project_utm** (*bool*) – If True, return bounding box as UTM-projected coordinates. * **return_crs** (*bool*) – If True, and project_utm is True, then return the projected CRS too. ### Returns *bbox or bbox, crs* – (left, bottom, right, top) or ((left, bottom, right, top), crs). ### Return type tuple[float, float, float, float] | tuple[tuple[float, float, float, float], *Any*] ``` -------------------------------- ### Download Driving Network for Manhattan Source: https://context7.com/gboeing/osmnx/llms.txt Downloads and models the driving network for a specified place. Inspect the type, number of nodes and edges, and attributes of a single node. ```python import osmnx as ox # Download the driving network for Manhattan G = ox.graph.graph_from_place("Manhattan, New York, USA", network_type="drive") print(type(G)) # print(len(G.nodes)) # e.g., 4580 print(len(G.edges)) # e.g., 12829 # Inspect a single node (OSM node ID → attributes) node_id = list(G.nodes)[0] print(G.nodes[node_id]) # {'y': 40.7127, 'x': -74.0059, 'street_count': 3, 'highway': 'traffic_signals', ...} ``` -------------------------------- ### osmnx.graph.graph_from_polygon Source: https://context7.com/gboeing/osmnx/llms.txt Downloads a network clipped to an arbitrary Shapely Polygon or MultiPolygon. ```APIDOC ## graph_from_polygon ### Description Downloads a network clipped to an arbitrary Shapely `Polygon` or `MultiPolygon`. ### Method `osmnx.graph.graph_from_polygon(polygon, network_type='drive', simplify=True, retain_all=False, truncate_by_edge=False, custom_filter=None, infrastructure=None, buffer_dist=None, timeout=180, save_graph=False, filepath=None, file_format='graphml', encoding='utf-8', log_console=False, use_cache=True, consolidate_intersections=True) ### Parameters * **polygon** (shapely.geometry.Polygon or shapely.geometry.MultiPolygon) - The polygon or multipolygon to clip the network to. * **network_type** (str) - The type of network to download (e.g., 'drive', 'walk', 'bike', 'all'). * **simplify** (bool) - Whether to simplify the graph topology. * **retain_all** (bool) - Whether to retain all disconnected components of the graph. * **truncate_by_edge** (bool) - Whether to truncate edges that cross the boundary. * **custom_filter** (str) - An optional custom filter for the Overpass API query. * **infrastructure** (str or list) - Optional OSM tags to filter network elements by infrastructure type. * **buffer_dist** (float) - Optional buffer distance in meters to expand the boundary. * **timeout** (int) - Timeout in seconds for the Overpass API request. * **save_graph** (bool) - Whether to save the downloaded graph to a file. * **filepath** (str) - The path to save the graph file. * **file_format** (str) - The format to save the graph file. * **encoding** (str) - The encoding to use when saving the graph file. * **log_console** (bool) - Whether to print console logs. * **use_cache** (bool) - Whether to use the cache for downloaded data. * **consolidate_intersections** (bool) - Whether to consolidate intersections. ### Request Example ```python import osmnx as ox from shapely.geometry import Polygon # Irregular hexagonal polygon (WGS84) coords = [ (-122.270, 37.870), (-122.265, 37.865), (-122.260, 37.868), (-122.262, 37.875), (-122.267, 37.877), (-122.270, 37.870), ] polygon = Polygon(coords) G = ox.graph.graph_from_polygon(polygon, network_type="all", simplify=True) ``` ### Response * **G** (networkx.MultiDiGraph) - The downloaded street network as a NetworkX MultiDiGraph object. ``` -------------------------------- ### Compute Basic Network Statistics Source: https://context7.com/gboeing/osmnx/llms.txt Calculate a comprehensive set of geometric and topological measures for a street network. The `area` parameter should be in square meters for density calculations. ```python import osmnx as ox from shapely.geometry import box G = ox.graph.graph_from_place("Piedmont, California", network_type="drive") # Area of the place boundary in square meters gdf_place = ox.geocoder.geocode_to_gdf("Piedmont, California") area_m2 = gdf_place.to_crs("EPSG:32610").geometry.area.iloc[0] stats = ox.stats.basic_stats(G, area=area_m2, clean_int_tol=15) print(f"Nodes (n): {stats['n']}") print(f"Edges (m): {stats['m']}") print(f"Avg streets per node: {stats['streets_per_node_avg']:.2f}") print(f"Total street length (m): {stats['street_length_total']:.0f}") print(f"Circuity avg: {stats['circuity_avg']:.4f}") print(f"Intersection count: {stats['intersection_count']}") print(f"Node density (per km²): {stats['node_density_km']:.2f}") print(f"Clean intersection count: {stats['clean_intersection_count']}") ``` -------------------------------- ### routing.shortest_path Source: https://context7.com/gboeing/osmnx/llms.txt Solves the shortest path(s) between origin/destination node pairs using Dijkstra's algorithm. Supports parallelization. ```APIDOC ## `routing.shortest_path` ### Description Solves the shortest path(s) between origin/destination node pairs using Dijkstra's algorithm. Supports parallelization. ### Method `osmnx.routing.shortest_path(G, orig, dest, weight='length', cpus=None)` ### Parameters - **G** (networkx.MultiDiGraph) - The graph to solve the shortest path in. - **orig** (int or list or array-like) - The origin node(s) or node ID(s). - **dest** (int or list or array-like) - The destination node(s) or node ID(s). - **weight** (str) - The edge attribute to use as the weight for shortest path calculation (e.g., 'length', 'travel_time'). Defaults to 'length'. - **cpus** (int) - The number of parallel processes to use for solving multiple O-D pairs. If None, uses a single process. ### Request Example ```python import osmnx as ox G = ox.graph.graph_from_place("Piedmont, California", network_type="drive") G = ox.routing.add_edge_speeds(G) G = ox.routing.add_edge_travel_times(G) # Identify two nodes orig = ox.distance.nearest_nodes(G, X=-122.2208, Y=37.8240) dest = ox.distance.nearest_nodes(G, X=-122.2050, Y=37.8120) # Shortest by distance (default) path_dist = ox.routing.shortest_path(G, orig, dest, weight="length") print(f"Path has {len(path_dist)} nodes") # Shortest by travel time path_time = ox.routing.shortest_path(G, orig, dest, weight="travel_time") # Solve many O-D pairs in parallel origs = [orig, dest] dests = [dest, orig] paths = ox.routing.shortest_path(G, origs, dests, weight="length", cpus=2) ``` ### Response - **path** (list) - A list of node IDs representing the shortest path from origin to destination. ``` -------------------------------- ### osmnx.graph.graph_from_bbox Source: https://github.com/gboeing/osmnx/blob/main/docs/source/user-reference.md Downloads and creates a street network graph within a specified latitude-longitude bounding box. Supports pre-defined network types or custom Overpass QL filters. ```APIDOC ## osmnx.graph.graph_from_bbox ### Description Download and create a graph within a lat-lon bounding box. This function uses filters to query the Overpass API: you can either specify a pre-defined network_type or provide your own custom_filter with Overpass QL. ### Parameters #### Path Parameters - **bbox** (tuple[float, float, float, float]) - Required - Bounding box as (left, bottom, right, top). Coordinates should be in unprojected latitude-longitude degrees (EPSG:4326). - **network_type** (str) - Optional - Defaults to 'all'. What type of street network to retrieve if custom_filter is None. Supported values: "all", "all_public", "bike", "drive", "drive_service", "walk". - **simplify** (bool) - Optional - Defaults to True. If True, simplify graph topology via the simplify_graph function. - **retain_all** (bool) - Optional - Defaults to False. If True, return the entire graph even if it is not connected. If False, retain only the largest weakly connected component. - **truncate_by_edge** (bool) - Optional - Defaults to False. If True, retain nodes the outside bounding box if at least one of the node’s neighbors lies within the bounding box. - **custom_filter** (str | list[str] | None) - Optional - A custom ways filter to be used instead of the network_type presets, e.g. ‘[“power”~”line”]’ or ‘[“highway”~”motorway|trunk”]’. If str, the intersection of keys/values will be used, e.g., ‘[maxspeed=50][lanes=2]’ will return all ways having both maxspeed of 50 and two lanes. If list, the union of the list items will be used, e.g., [‘[maxspeed=50]’, ‘[lanes=2]’] will return all ways having either maximum speed of 50 or two lanes. Also pass in a network_type that is in settings.bidirectional_network_types if you want the graph to be fully bidirectional. ### Returns - **G** (networkx.MultiDiGraph) - The resulting MultiDiGraph. ``` -------------------------------- ### osmnx.utils.citation Source: https://github.com/gboeing/osmnx/blob/main/docs/source/user-reference.md Print the OSMnx package’s citation information. ```APIDOC ## osmnx.utils.citation(style='bibtex') ### Description Print the OSMnx package’s citation information. Boeing, G. (2025). Modeling and Analyzing Urban Networks and Amenities with OSMnx. Geographical Analysis, 57(4), 567-577. doi:10.1111/gean.70009 ### Parameters * **style** (*str*) – {"apa", "bibtex", "ieee"} The citation format, either APA or BibTeX or IEEE. ### Returns * **None** ``` -------------------------------- ### osmnx.routing.shortest_path Source: https://github.com/gboeing/osmnx/blob/main/docs/source/user-reference.md Solves for the shortest path between origin(s) and destination(s) in a graph using Dijkstra’s algorithm. Can handle single nodes or iterables of nodes for origins and destinations, and supports parallel computation. ```APIDOC ## osmnx.routing.shortest_path Solve shortest path from origin node(s) to destination node(s). Uses Dijkstra’s algorithm. If orig and dest are single node IDs, this will return a list of the nodes constituting the shortest path between them. If orig and dest are lists of node IDs, this will return a list of lists of the nodes constituting the shortest path between each origin-destination pair. If a path cannot be solved, this will return None for that path. You can parallelize solving multiple paths with the cpus parameter, but be careful to not exceed your available RAM. See also k_shortest_paths to solve multiple shortest paths between a single origin and destination. For additional functionality or different solver algorithms, use NetworkX directly. ### Parameters * **G** (*networkx.MultiDiGraph*) – Input graph. * **orig** (*int* *|* *Iterable* *[**int* *]*) – Origin node ID(s). * **dest** (*int* *|* *Iterable* *[**int* *]*) – Destination node ID(s). * **weight** (*str*) – Edge attribute to minimize when solving shortest path. * **cpus** (*int* *|* *None*) – How many CPU cores to use if multiprocessing. If None, use all available. If you are multiprocessing, make sure you protect your entry point: see the Python docs for details. ### Returns *path* – The node IDs constituting the shortest path, or, if orig and dest are both iterable, then a list of such paths. ### Return type list[int] | None | list[list[int] | None] ``` -------------------------------- ### requests_kwargs Source: https://github.com/gboeing/osmnx/blob/main/docs/source/user-reference.md Optional keyword arguments to pass to the requests package when connecting to APIs. This can be used for authentication or to provide a path to a local certificate file. Refer to the requests package advanced documentation for options like auth, cert, verify, and proxies. ```APIDOC requests_kwargs: Optional keyword args to pass to the requests package when connecting to APIs, for example to configure authentication or provide a path to a local certificate file. More info on options such as auth, cert, verify, and proxies can be found in the requests package advanced docs. Default is {}. ``` -------------------------------- ### Download Network within Polygon Source: https://context7.com/gboeing/osmnx/llms.txt Downloads a network clipped to an arbitrary Shapely Polygon or MultiPolygon. The resulting graph's Coordinate Reference System (CRS) is printed. ```python import osmnx as ox from shapely.geometry import Polygon # Irregular hexagonal polygon (WGS84) coords = [ (-122.270, 37.870), (-122.265, 37.865), (-122.260, 37.868), (-122.262, 37.875), (-122.267, 37.877), (-122.270, 37.870), ] polygon = Polygon(coords) G = ox.graph.graph_from_polygon(polygon, network_type="all", simplify=True) print(f"Graph CRS: {G.graph['crs']}") ``` -------------------------------- ### _get_paths_to_simplify Source: https://github.com/gboeing/osmnx/blob/main/docs/source/internals-reference.md Generate all the paths to be simplified between endpoint nodes. This is an internal helper function. ```APIDOC ## _get_paths_to_simplify(G, node_attrs_include, edge_attrs_differ) ### Description Generate all the paths to be simplified between endpoint nodes. The path is ordered from the first endpoint, through the interstitial nodes, to the second endpoint. ### Parameters * **G** (*nx.MultiDiGraph*) – Input graph. * **node_attrs_include** (*Iterable* *[**str* *]* *|* *None*) – Node attribute names for relaxing the strictness of endpoint determination. A node is always an endpoint if it possesses one or more of the attributes in node_attrs_include. * **edge_attrs_differ** (*Iterable* *[**str* *]* *|* *None*) – Edge attribute names for relaxing the strictness of endpoint determination. A node is always an endpoint if its incident edges have different values than each other for any attribute in edge_attrs_differ. ### Yields *path_to_simplify* ### Return type Iterator[list[int]] ``` -------------------------------- ### osmnx._http._get_http_headers Source: https://github.com/gboeing/osmnx/blob/main/docs/source/internals-reference.md Updates the default requests HTTP headers with OSMnx-specific information, allowing customization of user agent, referer, and accept language. ```APIDOC ## osmnx._http._get_http_headers(, user_agent=None, referer=None, accept_language=None) ### Description Update the default requests HTTP headers with OSMnx information. ### Parameters #### Query Parameters - **user_agent** (str | None) - Optional - The user agent. If None, use settings.http_user_agent value. - **referer** (str | None) - Optional - The referer. If None, use settings.http_referer value. - **accept_language** (str | None) - Optional - The accept language. If None, use settings.http_accept_language value. ### Returns #### Success Response (200) - **headers** (dict[str, str]) - The updated HTTP headers. ### Return type dict[str, str] ``` -------------------------------- ### _save_graph_xml(G, filepath, way_tag_aggs, encoding='utf-8') Source: https://github.com/gboeing/osmnx/blob/main/docs/source/internals-reference.md Save graph to disk as an OSM XML file. ```APIDOC ## osmnx._osm_xml._save_graph_xml(G, filepath, way_tag_aggs, encoding='utf-8') ### Description Save graph to disk as an OSM XML file. ### Parameters * **G** (*networkx.MultiDiGraph*) - Unsimplified, unprojected graph to save as an OSM XML file. * **filepath** (*str | Path | None*) - Path to the saved file including extension. If None, use default settings.data_folder/graph.osm. * **way_tag_aggs** (*dict[str, Any] | None*) - Keys are OSM way tag keys and values are aggregation functions. Allows user to aggregate graph edge attribute values into single OSM way values. If None, or if some tag’s key does not exist in the dict, the way attribute will be assigned the value of the first edge of the way. * **encoding** (*str*) - The character encoding of the saved OSM XML file. ### Return type None ``` -------------------------------- ### Save and Load GraphML Files with OSMnx Source: https://context7.com/gboeing/osmnx/llms.txt Saves and loads graphs as GraphML files, preserving all OSMnx-specific attribute types on round-trip. Supports custom dtype conversion for specific attributes during loading. ```python import osmnx as ox G = ox.graph.graph_from_place("Piedmont, California", network_type="drive") # Save ox.io.save_graphml(G, filepath="piedmont_drive.graphml") # Load — attribute dtypes are automatically restored G2 = ox.io.load_graphml("piedmont_drive.graphml") print(type(G2.edges[list(G2.edges)[0]["length"]])) # # Custom dtype conversion import osmnx.io as oxio G3 = ox.io.load_graphml( "piedmont_drive.graphml", node_dtypes={"my_bool_attr": oxio._convert_bool_string}, ) ``` -------------------------------- ### Download Public Network near Address Source: https://context7.com/gboeing/osmnx/llms.txt Geocodes an address and downloads the public transit network within a specified distance. Inspect edge attributes to understand network details. ```python import osmnx as ox G = ox.graph.graph_from_address( "Empire State Building, New York, NY", dist=800, dist_type="network", network_type="all_public", ) # Inspect edge attributes u, v, k, data = next(iter(G.edges(keys=True, data=True))) print(data) # {'osmid': 123456, 'oneway': True, 'length': 87.3, 'highway': 'secondary', ...} ``` -------------------------------- ### Project Graph to UTM or Specified CRS Source: https://context7.com/gboeing/osmnx/llms.txt Project a graph from WGS84 to an appropriate UTM zone or any specified Coordinate Reference System (CRS). Can also project back to WGS84. ```python import osmnx as ox G = ox.graph.graph_from_place("Piedmont, California", network_type="drive") print(G.graph["crs"]) # Auto-select UTM zone G_proj = ox.projection.project_graph(G) print(G_proj.graph["crs"]) # Project to a specific CRS G_3857 = ox.projection.project_graph(G, to_crs="EPSG:3857") print(G_3857.graph["crs"]) # Project back to WGS84 G_latlong = ox.projection.project_graph(G_proj, to_latlong=True) print(G_latlong.graph["crs"]) ``` -------------------------------- ### osmnx.graph.graph_from_point Source: https://github.com/gboeing/osmnx/blob/main/docs/source/user-reference.md Downloads and creates a graph within some distance of a lat-lon point. This function uses filters to query the Overpass API. You can either specify a pre-defined network_type or provide your own custom_filter with Overpass QL. ```APIDOC ## osmnx.graph.graph_from_point ### Description Downloads and creates a graph within some distance of a lat-lon point. This function uses filters to query the Overpass API. You can either specify a pre-defined network_type or provide your own custom_filter with Overpass QL. ### Parameters #### Path Parameters - **center_point** (tuple[float, float]) - Required - The (lat, lon) center point around which to construct the graph. Coordinates should be in unprojected latitude-longitude degrees (EPSG:4326). - **dist** (float) - Required - Retain only those nodes within this many meters of center_point, measuring distance according to dist_type. #### Query Parameters - **dist_type** (str) - Optional - Defaults to "bbox". If "bbox", retain only those nodes within a bounding box of dist length/width. If "network", retain only those nodes within dist network distance of the nearest node to center_point. - **network_type** (str) - Optional - Defaults to "all". What type of street network to retrieve if custom_filter is None. Options include: "all", "all_public", "bike", "drive", "drive_service", "walk". - **simplify** (bool) - Optional - Defaults to True. If True, simplify graph topology with the simplify_graph function. - **retain_all** (bool) - Optional - Defaults to False. If True, return the entire graph even if it is not connected. If False, retain only the largest weakly connected component. - **truncate_by_edge** (bool) - Optional - Defaults to False. If True, retain nodes the outside bounding box if at least one of the node’s neighbors lies within the bounding box. - **custom_filter** (str | list[str] | None) - Optional - A custom ways filter to be used instead of the network_type presets, e.g. ‘[“power”~”line”]’ or ‘[“highway”~”motorway|trunk”]’. If str, the intersection of keys/values will be used, e.g., ‘[maxspeed=50][lanes=2]’ will return all ways having both maxspeed of 50 and two lanes. If list, the union of the list items will be used, e.g., [‘[maxspeed=50]’, ‘[lanes=2]’] will return all ways having either maximum speed of 50 or two lanes. Also pass in a network_type that is in settings.bidirectional_network_types if you want the graph to be fully bidirectional. ### Returns - **G** (networkx.MultiDiGraph) - The resulting MultiDiGraph. ### Notes Very large query areas use the utils_geo._consolidate_subdivide_geometry function to automatically make multiple requests: see that function’s documentation for caveats. ``` -------------------------------- ### osmnx._http._check_cache Source: https://github.com/gboeing/osmnx/blob/main/docs/source/internals-reference.md Checks if a given key exists in the cache and returns the file path if found. ```APIDOC ## osmnx._http._check_cache ### Description Check if a key exists in the cache, and return its cache file path if so. ### Parameters **key** (*str*) – The key to look for in the cache. ### Returns *cache_filepath* – Filepath to cached data for key if it exists, otherwise None. * **Return type:** *Path* | None ```