爱听歌的炒饭 · 荣耀平板7屏幕总成-荣耀平板7屏幕总成促销价 ...· 3 周前 · |
失落的鸡蛋面 · 2023五一假期长沙交通出行攻略(拥堵路段+ ...· 3 周前 · |
呐喊的罐头 · typescript ...· 1 月前 · |
奔放的熊猫 · 长江学者特聘教授到岗时间公示-云南大学党委教 ...· 2 月前 · |
帅气的玉米 · Microsoft Copilot ...· 2 月前 · |
If you use OSMnx in your work, please cite the
journal article
.
OSMnx is a Python package to retrieve, model, analyze, and visualize street networks from OpenStreetMap. Users can download and model walkable, drivable, or bikeable urban networks with a single line of Python code, and then easily analyze and visualize them. You can just as easily download and work with amenities/points of interest, building footprints, elevation data, street bearings/orientations, and network routing. If you use OSMnx in your work, please download/cite the paper here .
In a single line of code, OSMnx lets you download, model, and visualize the street network for, say, Modena Italy:
import osmnx as ox ox.plot_graph(ox.graph_from_place('Modena, Italy'))( Note that this blog post is not updated with every new release of OSMnx. For the latest, see the official documentation and usage examples . )
OSMnx is on GitHub and you can install it with conda. If you’re interested in OSMnx but don’t know where to begin, check out this guide to getting started with Python .
Check out the documentation and usage examples for details on using each of the following features:
There are many usage examples and tutorials in the examples repo . I’ll demonstrate 5 basic use cases for OSMnx in this post:
To acquire administrative boundary GIS data, one must typically track down shapefiles online and download them. But what about for bulk or automated acquisition and analysis? There must be an easier way than clicking through numerous web pages to download shapefiles one at a time. With OSMnx, you can download place shapes from OpenStreetMap (as geopandas GeoDataFrames) in one line of Python code – and project them to UTM (zone calculated automatically) and visualize in just one more line of code:
import osmnx as ox city = ox.geocode_to_gdf('Berkeley, California') ax = ox.project_gdf(city).plot() _ = ax.axis('off')You can just as easily get other place types, such as neighborhoods, boroughs, counties, states, or nations – any place geometry in OpenStreetMap:
place1 = ox.geocode_to_gdf('Manhattan, New York City, New York, USA') place2 = ox.geocode_to_gdf('Cook County, Illinois') place3 = ox.geocode_to_gdf('Iowa, USA') place4 = ox.geocode_to_gdf('Bolivia')Or you can pass multiple places into a single query to save a single shapefile or geopackage from their geometries. You can do this with cities, states, countries or any other geographic entities:
places = ox.geocode_to_gdf(['Botswana', 'Zambia', 'Zimbabwe']) places = ox.project_gdf(places) ax = places.plot() _ = ax.axis('off')To acquire street network GIS data, one must typically track down Tiger/Line roads from the US census bureau, or individual data sets from other countries or cities. But what about for bulk, automated analysis? And what about informal paths and pedestrian circulation that Tiger/Line ignores? And what about street networks outside the United States? OSMnx handles all of these uses.
OSMnx lets you download street network data and build topologically-corrected street networks, project and plot the networks, and save the street network as SVGs, GraphML files, or shapefiles for later use. The street networks are directed and preserve one-way directionality. You can download a street network by providing OSMnx any of the following (demonstrated in the examples below):
You can also specify several different network types:
You can download and construct street networks in a single line of code using these various techniques:
This gets the drivable street network within some lat-long bounding box, in a single line of Python code, then projects it to UTM, then plots it:
G = ox.graph_from_bbox(37.79, 37.78, -122.41, -122.43, network_type='drive') G_projected = ox.project_graph(G) ox.plot_graph(G_projected)You can get different types of street networks by passing a network_type argument, including driving, walking, biking networks (and more).
This gets the street network within 0.75 km (along the network) of a latitude-longitude point:
G = ox.graph_from_point((37.79, -122.41), dist=750, network_type='all') ox.plot_graph(G)You can also specify a distance in cardinal directions around the point, instead of along the network.
This gets the street network within 1 km (along the network) of the Empire State Building:
G = ox.graph_from_address('350 5th Ave, New York, New York', network_type='drive') ox.plot_graph(G)You can also specify a distance in cardinal directions around the address, instead of along the network.
Just load a shapefile with geopandas, then pass its shapely geometry to OSMnx. This gets the street network of the Mission District in San Francisco:
G = ox.graph_from_polygon(mission_shape, network_type='drive') ox.plot_graph(G)Here’s where OSMnx shines. Pass it any place name for which OpenStreetMap has boundary data, and it automatically downloads and constructs the street network within that boundary. Here, we create the driving network within the city of Los Angeles:
G = ox.graph_from_place('Los Angeles, California', network_type='drive') ox.plot_graph(G)You can just as easily request a street network within a borough, county, state, or other geographic entity. You can also pass a list of places (such as several neighboring cities) to create a unified street network within them. This list of places can include strings and/or structured key:value place queries:
places = ['Los Altos, California, USA', {'city':'Los Altos Hills', 'state':'California'}, 'Loyola, California'] G = ox.graph_from_place(places, network_type='drive') ox.plot_graph(G)In general, US street network data is fairly easy to come by thanks to Tiger/Line shapefiles. OSMnx makes it easier by making it available with a single line of code, and better by supplementing it with all the additional data from OpenStreetMap. However, you can also get street networks from anywhere in the world – places where such data might otherwise be inconsistent, difficult, or impossible to come by:
G = ox.graph_from_place('Modena, Italy') ox.plot_graph(G) G = ox.graph_from_place('Belgrade, Serbia') ox.plot_graph(G) G = ox.graph_from_address('Maputo, Mozambique', distance=3000) ox.plot_graph(G) G = ox.graph_from_address('Bab Bhar, Tunis, Tunisia', distance=3000) ox.plot_graph(G)Note: you can also topologically consolidate nearby intersections.
Simplification is done by OSMnx automatically under the hood, but we can break it out to see how it works. OpenStreetMap nodes can be weird: they include intersections, but they also include all the points along a single street segment where the street curves. The latter are not nodes in the graph theory sense, so we remove them algorithmically and consolidate the set of edges between “true” network nodes into a single edge.
When we first download and construct the street network from OpenStreetMap, it looks something like this:
We want to simplify this network to only retain the nodes that represent the junction of multiple streets. OSMnx does this automatically. First it identifies all non-intersection nodes:
And then it removes them, but faithfully maintains the spatial geometry of the street segment between the true intersection nodes:
Above, all the non-intersection nodes have been removed, all the true intersections (junctions of multiple streets) remain in blue, and self-loop nodes are in purple. There are two simplification modes: strict and non-strict. In strict mode (above), OSMnx considers two-way intersections to be topologically identical to a single street that bends around a curve. If you want to retain these intersections when the incident edges have different OSM IDs, use non-strict mode:
OSMnx can save the street network to disk as a GraphML file to work with later in Gephi or networkx. Or it can save the network (such as this one, for the New York urbanized area) as ESRI shapefiles or GeoPackages to work with in any GIS:
OSMnx can also save street networks as SVG files for design work in Adobe Illustrator:
You can then load any network you saved as GraphML back into OSMnx to calculate network stats, solve routes, or visualize it.
Since this is the whole purpose of working with street networks, I’ll break analysis out in depth in a future dedicated post. But I’ll summarize some basic capabilities briefly here. OSMnx is built on top of NetworkX, geopandas, and matplotlib, so you can easily analyze networks and calculate spatial network statistics:
G = ox.graph_from_place('Santa Monica, California', network_type='walk') basic_stats = ox.basic_stats(G) print(basic_stats['circuity_avg']) extended_stats = ox.extended_stats(G, bc=True) print(extended_stats['betweenness_centrality_avg'])The stats are broken up into two primary functions: basic and extended. The extended stats function also has optional parameters to run additional advanced measures.
You can also calculate and plot shortest-path routes between points, taking one-way streets into account:
G = ox.graph_from_place('Piedmont, CA, USA', network_type='drive') route = nx.shortest_path(G, orig, dest) fig, ax = ox.plot_graph_route(G, route, route_linewidth=6, node_size=0, bgcolor='k')You can impute missing edge speeds and calculate edge travel times (see example ) to contrast shortest paths by distance (red) vs by travel time (blue):
You can also visualize the compass orientation of street networks around the world:
Allan Jacobs famously compared several cities’ urban forms through figure-ground diagrams of 1 square mile of each’s street network in his book Great Streets . We can re-create this automatically and computationally with OSMnx:
These figure-ground diagrams are created completely with OSMnx.
OSMnx lets you download spatial geometries and model, project, visualize, and analyze real-world street networks. It allows you to automate the data collection and computational analysis of street networks for powerful and consistent research, transportation planning, and urban design. OSMnx is built on top of NetworkX, matplotlib, and geopandas for rich network analytic capabilities, beautiful and simple visualizations, and fast spatial queries with r-tree, kd-tree, and ball-tree indexes.
OSMnx is open-source and on GitHub . You can download/cite the paper here .
Great article!
I have the following questions:
1- How can I convert the graph metrics (basic and extended) to a geopandas frame?
2- Can I get graph metrics for a specific MGRS grid, for example within a 100×100 meters grid?
Thank you in advance.
Thanks for this great article gboeing.
Suppose we run this command:
import osmnx as ox
ox.plot_graph(ox.graph_from_place('Modena, Italy'), network_type='drive'))
How could we fine out whether a GPS Coordinate lies on a specific road ?
e.g. if we assign an id to each road (in the network), then give a list of gps lat and long, could we determine which (lat, long) combination lies on which road id ?
Hi Geoff,
thank you for this great resource!
How can we export the data as a GeoJSON file? Is this possible?
Do you know how can we use this data to build the city blocks from the street network?
Thanks!
Thanks. I’ll be adding GeoJSON export in an upcoming version. It’ll be a simple feature to add. City blocks is a good question, and something I am currently researching. The ambiguity lies in the definition of a city block. One thing you can do is polygonize your set of edge lines and treat the polygons as blocks. There will be some strange artifacts there, but it’s a proxy. Looking forward to your suggestions as you delve into this.
Hey Geoff, amazing work! OSMnx is really easy to use and incredibly useful! I was wondering whether you already implemented the GeoJSON export. Thank you.
Best,
Chris
Hi Geoff,
First of all, great work! Congrats! Second, I’d like to ask you how the tool manages multiple parallel lines (e.g., big roads with multiple lanes, footpaths, cycle ways etc.) and roundabouts. Does it shrink everything in single neat lines and intersections?
Thanks in advance,
Alessandro
Thanks. OSMnx handles edges however OSM provides them. That said, roads with multiple lanes are represented as a single edge (and the edge has optional attributes of number of lines, width, road type, etc.). Divided roads are represented as directed edges going in reciprocal directions, but offset from each other such that they are (approximately) center-lines for each direction. Roundabouts are represented as roundabouts, as they are on OSM. Reducing parallel, nearby paths to single edges is a non-trivial computational task.
Hi Geoff,
this tool is amazing. You’ve done a really great job.
I’d like to ask you if there is any way to “disable” nodes, which are at the ends of roads in order to extract “true” intersections only?
Thanks a lot!
Yes you can easily identify which nodes are actual intersections, vs dead-ends. OSMnx creates a graph attribute that states how many physical streets are connected to each node. Any node with >1 is an intersection. For example:
G = ox.graph_from_place('Piedmont, California, USA', network_type='drive')
streets_per_node = G.graph['streets_per_node']
node_ids = set(G.nodes())
intersections = [node for node, count in streets_per_node.items() if count>1]
dead_ends = [node for node, count in streets_per_node.items() if count==1]
This looks awesome. I just started playing with it and noticed your example for `ox.graph_from_bbox()` you pass a list and a network_type, however when I try that it gives me a “need at least 4” parameters error. Seems to work fine if I pass each of the bbox coordinates separately, eg like so: `ox.graph_from_bbox(bbox[0], bbox[1], bbox[2], bbox[3], network_type=’drive_service’)`.
Cheers.
Wow! Amazing work! For real… awesome!
Congrats on such a useful and simple-to-use library!
Rafael Pereira mentioned your work on a post of his blog… I will definitely be following you from now on!
#ThanksGeoff
Hi Geoff,
Congratulations for this neat piece of code. I’ll try to use it for my studies. I do exactly what this tool is meant for on a daily basis. Will hopefully come up with more to discuss.
PhD in Geomatics Engg.
Hi Geoff,
Could you share the code you used to make the Jacobsesque figure-ground diagrams? Again, this is a fabulous tool for urban designers everywhere.
Best,
Yasir
Hi Geoff,
your work is awesome!congrats!
Is this possible to load data as a big matrix into the memory?
thanks a lot.
Hello
Nice work !
I found your article because I am looking for a way to extract contours from OSM and draw them on a tiles. For example, using folium, you can easily add markers or draw polygons on the map.
But it is sometimes not easy to find the coordinates of administrative regions (out of USA). With your module, with simple requests you can easily get it.
Is there a way to do plot on a tiles with OSMnx ? or Do you know another module which can be used to do this ?
Thanks
Hey, I’d love to try this but I’m having trouble with an rtree libspatialindex_c dependency, I’ve installed via conda-forge to no avail, and after looking at the rtree library it looks like a pretty common thing.
Is it possible the rtree dependency could be removed? Have you dealt with rtree c lib dependencies before?
Also the project looks really cool!
Thanks in advance!
What platform are you on? If you’re on Linux, you can install libspatialindex with apt-get. If you’re on Windows, you can install rtree (and its C extensions) easily with Gohlke’s binaries . I don’t have a Mac, but my students who are Mac users got rtree installed and working using conda and either the conda-forge or the IOOS channel. Make sure you’re using the latest versions of rtree (0.8.3) and libspatialindex. If you have any other problems, you can open an issue in the GitHub repo (or the relevant repo if someone’s dependency is broken for your platform).
Hello,
Fantastic work, thank you for sharing!
I got experience in Python but I am pretty new to the whole geospatial world – so sorry for the newbie question.
I would like to ask you how could I use osmnx to load my locally saved (road)-network and parse it correctly into networkx in order to be able perform the operations that you show (plotting, routing, and computing network metrics).
The locally saved road network is optimally in shapefile or geojson format. But probably I could also convert it prior (with command line operation or QGIS) to OSM format or into Spatial Database.
Can this be implemented with little effort? Are you planning to make this type of operation part of the main package?
Thanks
Hi Geoff – this is pretty great! Any way to integrate transit networks into this – e.g. bus and subway routes?
Thanks!
Hello
Fantastic work !
I would like to ask you, how could I load back the saved shapefile into a networkx graph object. Is this operation feasible?
Alternatively could I load locally saved files in OSM or spatial database format as graph, and then perform routing, network simplification in osmnx ?
X-Ray Your City's Street Network, With a Bit of Code - Top 10 RSS Feeds | Follow the Most Popular RSS Feeds says: Thanks so much for the information. Seems like this could be very helpful. Is it possible for you to do an follow up explanation for someone with GIS experience but no coding experience? This will help agencies who want to perform such analysis but currently do not have the coding experience.
Thank you
Great project!
A general question – What would be the most efficient way to load graph into osmnx? what format is optimal?
loading data for an entire country using graph_from_place() can be a bit time consuming.
I get this error:
File “C:\Python27\lib\site-packages\rtree\core.py”, line 116, in
raise OSError(“could not find or load spatialindex_c.dll”)
OSError: could not find or load spatialindex_c.dll
Thanks for sharing this great tool!
Have you ever considered implementing isolines computation on top of it? I’m thinking to adopt OSMnx to calculate all the routes starting from a list of locations (their projections on the network geometries) and going X meters far.
PS: in my case the routes have no one-way or turn restrictions being pedestrian routes.
It sounds great! Today I’ve been working on it, trying various solutions based on OSMnx output (even one with the spatial output imported in a spatial DB).
Now I’m testing another path with GeoPandas and NetworkX.
Hi, gobeing, when I run the following setences:
G = ox.graph_from_place(‘Los Angeles, California’, network_type=’drive’)
ox.plot_graph(G)
it shows nothing, I am confused
This is similar to the tool from “A protocol to convert spatial polyline data to network formats and applications to world urban road networks”
https://www.nature.com/articles/sdata201646
They’ve made an ArcGIS, QGIS, and Python version.
Hi Geoff,
Indeed a very useful and well put together code. I wish I had similar skills! Congratulations!
I have noticed you hard coded the Overpass API URL and there is no helper function to set the target API to a different instance except the official one. I have hosted Overpass API and OSM database with full global network to avoid overloading the official service and allow for more demanding queries. So far we use it with much success on full-scale POI’s city analysis and multi-agent transport simulations.
I was wondering if you would consider enabling custom setup of Overpass API URL via some utility function or setting variable.
Greate work!
With respect,
Catalin
Great tool! The code for visualising cul-de-sacs is not 100% correct anymore, it seems, on the version I am using. Should be:
streets_per_node, not streets_per_intersection.
Hey, this tool is awesome. Thanks very much for sharing it with us.
I’m developing my final work at my university and I have to know the distance between the point from an gived area (north, south, east, west).
Can I get them with your tool? Is there some method that I can download the street distances from a gived north, south, east and west?
Thanks for your attention!
Are you saying you’d like to download a street network within some north, south, east, west bounding box? If so, OSMnx has a built-in function to do this. You can see it demonstrated in the example notebook: https://github.com/gboeing/osmnx-examples/blob/master/notebooks/01-overview-osmnx.ipynb . You can then easily calculate distances between points.
I was trying to say that I need to download de matrix distances from a gived area.
For example: I have an area with max(lat, lon) and min(lat, lon) and I need to download the matrix distance from each point of this area to the others points from this area. I need to use the Dikjstra’s method to calculate the minimum path.
Can I get the matrix distance with your tool?
Thanks for your attention!
Hi. I have a question regarding the intersection of the streets in a city, say Berlin.
how can I get a list of intersections as well as the link between two intersections and the length of it?
thank you very much in advanced!
Hello gboeing congrats
G = ox.graph_from_address(‘N. Sicily Pl., Chandler, Arizona’, distance=800, network_type=’drive’)
route = nx.shortest_path(G, origin, destination)
ox.plot_graph_route(G, route)
error: name ‘nx’ is not defined
how i define nx?
thanks your help.
thanks again
Hi Geoff,
I was fascinated to discover such a useful tool as OSMnx. Keep up the good work!
Started playing around with the examples from the docs. Plotting shape worked just fine. But running:
G = ox.graph_from_place(‘Iowa City, IA, USA’, network_type=’drive’)
ox.plot_graph(ox.project_graph(G))
returns: ‘TypeError: ‘method’ object is not subscriptable’
Any ideas on what caused the error or how it could be remedied?
Dear Geoff,
I am just a novice when it comes to programmatic data-visualization in Python, but I was wondering if there is a way to plot both the osmnx objects and scatterplot via standard matplotlib plt.scatter function?
Suppose I wanted to plot a road network constructed in osmnx together with the school size (scatter, with different sizes / colors). Is there a way to do it without exporting graph to *shp and then plotting it all together in another library like cartopy / basemap?
Hi Geoff,
Excellent tool and it is working smooth. Would it be possible to load an osm file which is already downloaded? I would like to play around with higher tier road networks on larger geographical areas (motorways, primary roads etc).
Thanks! Elco
Hello gboeing!
This is my first time here, and I’m not sure if it’s the proper place to ask.
However, as @ElcoK asked, I have been looking in the documentation of OSMnx for a way to load an OSM file that was saved on local disk.
Is it possible now? if so, are there any examples about that?
Thank you!
Hello, dear Geoff.
Thank you for your contribution.
I have a question, can you convert or read a graphml file to graphX and work with mapreduce in Spark?
I’m doing a doctorate in Ecuador and I’m reviewing your tool and hadoop to see if I can do anything else.
thanks, see you
Thank you very much! I will look into networkx for the adjacency matrix. However, do you mind to explain a little more for outputting node’ data dictionaries as a txt file?
Sincerely,
Hello, dear Geoff.
Thank you for your contribution.
I have a question, can you convert or read a graphml file to graphX and work with mapreduce in Spark?
I’m doing a doctorate in Ecuador and I’m reviewing your tool and hadoop to see if I can do anything else.
thanks, see you
Dear Geoff,
i just installed the Miniconda and run the conda install -c conda-forge osmx in the conda.exe. Then everything seemed to be installed but then at the end i got the following error: ERROR conda.core.link:_execute_actions: An error occurred while installing package ‘conda-forge: jupyter_core-4.4.0-py_0. Do you know exactly what it is?
Hi Geoff,
I just installed osmnx (using conda), and tried to import it, but got the following error —
ImportError: dlopen(/Users/apal/anaconda2/lib/python2.7/site-packages/fiona/ogrext.so, 2): Library not loaded: @rpath/libuuid.1.dylib
Referenced from: /Users/apal/anaconda2/lib/libgdal.20.dylib
Reason: image not found
Do you know any fixes?
Thanks for using OSMnx. If you’re having any trouble with it, feel free to peruse its closed issues on GitHub, or open a new one if there’s a bug. It looks like you used conda to install it, so check out the conda-forge issue and answer here: https://github.com/conda-forge/osmnx-feedstock/issues/14#issuecomment-351447160
Hi Geoff,
Thank you very much for this nice work!
I was wondering if it is possible to obtain, in addition to the map, data about the plotted graph (e.g. links, nodes, connectivity, lengths).
Best,
Michele
Hi Geoff,
The tool is amazing, I have a question though
How does the OSMnx recognize in which direction traffic is allowed for oneway roads?? In the direction of OSM digitalization? Coz when I save a network (OSMnx) as shapefile and open it in Qgis, the direction of lines (oneways) does not correspond with the original data downloaded from overpass.
Thanks for reply
Andre
Hi Dear Geoff,
Can you help me locate the hospitals nodes on a map,
I want to see the Betweeneess centrality of hospitals
thanks for your great help and contribution
Dear Geoff,
Could you please tell me if it is possible to extract the faces of street network graph (blocks surrounded by streets)?
Thanks
Hi there!
Great work and I’m looking forward very much to progressing further through the tutorials and papers.
I’ve been trying to get Edinburgh in Scotland to show up but for some reason the name taken from OSM doesnt work. Would you be able to give me any pointers as to why this may be?
As a side note this is how I’ve been getting other areas such as Melbourne to produce graphs. Hope this info helps in the query!
Hi Geoff,
Thanks a lot for your work on OSMnx. It is really cool tool and I have been enjoying using it for my research. Could you please provide (or forward to) a more detailed steps for obtaining graph from a shaplefile polygon?
I have a question regarding to obtaining a street network from polygons. I have opened a GDB file in ArcMap and saved it in shapefile format, which has been used as input for the ox.graph_from_polygon command. However, I have been seeing this error and haven’t been able to figure out why.
%%%%Code Begins%%%%%%
import osmnx as ox
import networkx as nx
import geopandas as gpd
SN_16=gpd.read_file(r’C:\Users\*******\SN_16.shp’)
G_16 = ox.graph_from_polygon(SN_16, network_type=’drive’)
ox.plot_graph(G_16)
—————————————————————————
ValueError Traceback (most recent call last)
in ()
—-> 1 G_16 = ox.graph_from_polygon(SN_16, network_type=’drive’)
2 ox.plot_graph(G_16)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\osmnx\core.py in graph_from_polygon(polygon, network_type, simplify, retain_all, truncate_by_edge, name, timeout, memory, max_query_area_size, clean_periphery, infrastructure)
1665 # verify that the geometry is valid and is a shapely Polygon/MultiPolygon
1666 # before proceeding
-> 1667 if not polygon.is_valid:
1668 raise ValueError(‘Shape does not have a valid geometry’)
1669 if not isinstance(polygon, (Polygon, MultiPolygon)):
~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py in __nonzero__(self)
1119 raise ValueError(“The truth value of a {0} is ambiguous. ”
1120 “Use a.empty, a.bool(), a.item(), a.any() or a.all().”
-> 1121 .format(self.__class__.__name__))
1123 __bool__ = __nonzero__
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
I have been using Jupyter in Anaconda. I would greatly appreciate if anyone could comment on this.
Hey Geoff,
I am having a similar problem. The docs and examples don’t detail very well how to do this. In the examples, all I can find is:
calif = gpd.read_file(‘input_data/ZillowNeighborhoods-CA’)
mission_district = calif[(calif[‘CITY’]==’San Francisco’) & (calif[‘NAME’]==’Mission’)]
polygon = mission_district[‘geometry’].iloc[0]
G6 = ox.graph_from_polygon(polygon, network_type=’drive_service’)
I used this to open a geojson, then used iloc as well, and I am still getting no luck, on multiple files, with the message that it is not a valid polygon.
The documentation otherwise excludes the instructions regarding geopandas, and simply asks for a polygon. Maybe geojson is simply not supported, even if opened with geopandas and if geopandas can be used to show the geometry?
Hi Geoff
Thanks for this amazing and quite helpful resource.
One question: I am creating a graph from an osm file and then plotting it. While doing this, it is also plotting building along with the roads. Is there a way to remove buildings from this graph/just ignore buildings while creating a graph from that osm file?
Thanks
Hi Geoff,
Thank you for this easy-to-use tool.
I am wondering if there is a way to use shortest_path on multiple points to create a shortest route planner. (Travelling salesman problem)
Thank you
Hi Geoff,
I have been unable to work with any cities in Virginia. Using the examples provided, I am able to export city boundaries in various other states but when I try Virginia Beach (or any other city in Virginia) it prompts an error. Any clue as to what the issue may be?
import osmnx as ox
place = ox.gdf_from_place(‘Virginia Beach, Virginia’)
ox.plot_shape(ox.project_gdf(place))
Geoff,
Thank you very much. This worked perfectly and rectified the problem.
What a fantastic package you’ve provided. Thank you!
Kind Regards,
OMG, such a great idea! Found it there
https://meduza.io/shapito/2018/07/14/issledovatel-iz-ssha-pridumal-udivitelnuyu-vizualizatsiyu-ob-yasnyayuschuyu-ustroystvo-gorodov-a-my-s-ee-pomoschyu-posmotreli-na-rossiyskie
and was amazed. But sad that there is no web page for the application, I mean, if someone who is not familiar with Python wants to get the scheme for his city, it seems not so easy:(
So the question, can anyone help me to get the pic for one small town in Siberia called ‘Abakan’, pls, send to
[email protected]
.
I and all the Siberian bears will be very thankful!:)
Hi Geoff.
This is just a great tool and it is being super useful for urban morphology.
Quick question: Is it possible to extract parts of a loaded graph G?
What I’m trying to do is to divide the city according a regular grid and then compare the network statistics for each cell on the grid. I want to avoid a separate call to OSM server for each cell, and instead to use a previously saved .osm file for the whole area. So my approach would be:
1. Load the .osm file
2. Recursively get either the boundaries or the polygon for each cell and extract a sub-graph for the given cell.
3. Compute nx statistics for each subgraph.
4. Use a clustering algorithm to classify the cells into similar groups according their network characteristics.
I’m stuck on step 2. Any advice will be extremely helpful.
Best,
Daniel
Hi Geoff! First of all, it might be one of the best python package I’ve ever used. Congrats!!! Second, I would like to extract a road network of a whole country. For sure, I do not need a high level of of details. Ideally I want to retrieve only the biggest freeways of a territory. I think it might be possible by playing the infrastructure or the filter argument but I failed. Can you help me?
Hi Geoff,
Is there a way to draw a line across multiple points instead of just 2. Kind of like the Google maps multiple destinations. I thought of using nodes and edges information but I see that the graph just takes in the orig_node and dest_node and not a collection of nodes.
Thanks
Thanks. I got the plot_graph_routes working. So it stores the bunch of edges in an array for multiple destination. However it seems that destinations might have paths overlapping each other as each point-point distance is calculated individually. Is there a way to simplify and remove the redundant links between these points ?
Kind of like a minimum spanning tree ?
Thanks.
Hi Geoff,
I was wondering whether there is a way to map a given GPS point to its nearest edge, using your library?
Thank you!
When I was running:
city = ox.gdf_from_place(‘Berkeley, California’)
ox.plot_shape(ox.project_gdf(city))
I got the following errors
—————————————————————————
RuntimeError Traceback (most recent call last)
in ()
1 import osmnx as ox
2 city = ox.gdf_from_place(‘Berkeley, California’)
—-> 3 ox.plot_shape(ox.project_gdf(city))
~\Anaconda3\lib\site-packages\osmnx\projection.py in project_gdf(gdf, to_crs, to_latlong)
118 # project the GeoDataFrame to the UTM CRS
–> 119 projected_gdf = gdf.to_crs(utm_crs)
120 log(‘Projected the GeoDataFrame “{}” to UTM-{} in {:,.2f} seconds’.format(gdf.gdf_name, utm_zone, time.time()-start_time))
~\Anaconda3\lib\site-packages\geopandas\geodataframe.py in to_crs(self, crs, epsg, inplace)
441 else:
442 df = self.copy()
–> 443 geom = df.geometry.to_crs(crs=crs, epsg=epsg)
444 df.geometry = geom
445 df.crs = geom.crs
~\Anaconda3\lib\site-packages\geopandas\geoseries.py in to_crs(self, crs, epsg)
302 except TypeError:
303 raise TypeError(‘Must set either crs or epsg for output.’)
–> 304 proj_in = pyproj.Proj(self.crs, preserve_units=True)
305 proj_out = pyproj.Proj(crs, preserve_units=True)
306 project = partial(pyproj.transform, proj_in, proj_out)
~\Anaconda3\lib\site-packages\pyproj\__init__.py in __new__(self, projparams, preserve_units, **kwargs)
356 # on case-insensitive filesystems).
357 projstring = projstring.replace(‘EPSG’,’epsg’)
–> 358 return _proj.Proj.__new__(self, projstring)
360 def __call__(self, *args, **kw):
_proj.pyx in _proj.Proj.__cinit__()
RuntimeError: b’No such file or directory’
Any ideas on what caused the error?
Thanks
What can i do to fix this problem ?! I know the server was down – but requests dont work still :(((
I also noticed that yr app gets more nodes that openstreetmap per box – how can this happen ?
thnk you in advance!!!
Hi, Geoff! Your packages is awesome and very clean. Really a nice and useful work.
I have a short question and i didn’t find any related in StackOverflow, issues’ github, etc.
Me and my team working calculate some distances using NetworkX, downloading the OSM network directly from Geofabrik, but for a specific date. So, we do not know if your methods to get network from polygons (will) have a method to specific the OSM network date to be download. ¿Is there a way/a parameter to do that with your methods? It’s necessary compare data from 2016 with the OSM network from same year (month, etc) to get an coherent analysis instead of use the latest downloaded network.
Finally, ¿What datetime has download network when i use the method ‘get_from_point/polygon’?
Sorry for my bad english :D.
Thanks!
A question if you can help me please
how to convert a node 5489469349 to a coordinate lat, lon?
Best regards
Hi Geoff,
Since Several days I a trying finding the number of points (coordinates of data with lat and lon) that are within two nodes of a multi-graph I have obtained with the osmnx library. Basically, I want to count the number of car (equipped with GPS) that crossed an edge between two nodes.
Thanks so much for your help!
Federico
hello, proffessor I am very happy to meet with you.on your site. my name is Abdisa Bafikadu from Addis Ababa, Ethiopia I am road transport masters student from Addis Ababa Science and technology how I can use Osmnx for my research? my research is urban network analysis is that possible to use for developing country like our country Ethiopia?
Hi, I have a problem with my OSM project, I am trying to extract city blocks as polygons, I was able to get extract it for some points but it does not work universally, can anyone please help me? Link to my problem with code is here: https://stackoverflow.com/questions/60147207/single-positional-indexer-is-out-of-bounds
analysis of pedestrian accessibility of objects in Prague using data science / Veeam Software Blog / geek magazine – Developers says:
Hi Geoff,
My environment is python 3.7 and after installing OSMnx.
I try to run the demo as below.
import osmnx as ox
city = ox.gdf_from_place(‘Berkeley, California’)
ox.plot_shape(ox.project_gdf(city))
Then errors occur as:
D:\Anaconda\envs\osmnx_env37\python.exe G:/街景/hsv0212/OSM1.py
Traceback (most recent call last):
File “D:\Anaconda\envs\osmnx_env37\lib\site-packages\urllib3\connectionpool.py”, line 654, in urlopen
conn = self._get_conn(timeout=pool_timeout)
File “D:\Anaconda\envs\osmnx_env37\lib\site-packages\urllib3\connectionpool.py”, line 274, in _get_conn
return conn or self._new_conn()
File “D:\Anaconda\envs\osmnx_env37\lib\site-packages\urllib3\connectionpool.py”, line 964, in _new_conn
“Can’t connect to HTTPS URL because the SSL module is not available.”
urllib3.exceptions.SSLError: Can’t connect to HTTPS URL because the SSL module is not available.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File “D:\Anaconda\envs\osmnx_env37\lib\site-packages\requests\adapters.py”, line 449, in send
timeout=timeout
File “D:\Anaconda\envs\osmnx_env37\lib\site-packages\urllib3\connectionpool.py”, line 720, in urlopen
method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]
File “D:\Anaconda\envs\osmnx_env37\lib\site-packages\urllib3\util\retry.py”, line 436, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host=’nominatim.openstreetmap.org’, port=443): Max retries exceeded with url: /search?format=json&limit=1&dedupe=0&polygon_geojson=1&q=Berkeley%2C+California (Caused by SSLError(“Can’t connect to HTTPS URL because the SSL module is not available.”))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File “G:/街景/hsv0212/OSM1.py”, line 2, in
city = ox.gdf_from_place(‘Berkeley, California’)
File “D:\Anaconda\envs\osmnx_env37\lib\site-packages\osmnx\core.py”, line 68, in gdf_from_place
data = osm_polygon_download(query, limit=which_result)
File “D:\Anaconda\envs\osmnx_env37\lib\site-packages\osmnx\downloader.py”, line 282, in osm_polygon_download
response_json = nominatim_request(params=params, timeout=30)
File “D:\Anaconda\envs\osmnx_env37\lib\site-packages\osmnx\downloader.py”, line 334, in nominatim_request
response = requests.get(url, params=params, timeout=timeout, headers=get_http_headers())
File “D:\Anaconda\envs\osmnx_env37\lib\site-packages\requests\api.py”, line 76, in get
return request(‘get’, url, params=params, **kwargs)
File “D:\Anaconda\envs\osmnx_env37\lib\site-packages\requests\api.py”, line 61, in request
return session.request(method=method, url=url, **kwargs)
File “D:\Anaconda\envs\osmnx_env37\lib\site-packages\requests\sessions.py”, line 530, in request
resp = self.send(prep, **send_kwargs)
File “D:\Anaconda\envs\osmnx_env37\lib\site-packages\requests\sessions.py”, line 643, in send
r = adapter.send(request, **kwargs)
File “D:\Anaconda\envs\osmnx_env37\lib\site-packages\requests\adapters.py”, line 514, in send
raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host=’nominatim.openstreetmap.org’, port=443): Max retries exceeded with url: /search?format=json&limit=1&dedupe=0&polygon_geojson=1&q=Berkeley%2C+California (Caused by SSLError(“Can’t connect to HTTPS URL because the SSL module is not available.”))
Process finished with exit code 1
Do you hava any idea abt that error? I have been looking at ways to figure it out but it still remains unsolved.
Thanks
Vincent
Hi Vincent, Geoff,
Did you have any idea about this error ? I got the same one this afternoon and didn’t manage to figure it out.
Thanks,
Kind Regards,
HI Thanks for the library, it is of great help.
I wonder how can we save the shortest route into disk as shpfile format data?
Thanks a lot.
Hello Mr. Geoff,
I am a Phd student in computer science, and i am working on finding the optimal path in a smart city, so i found your project OSMnx, and i think that it is an interesting tool to analyse street networks.
So, i would like to ask you please, if i can implement and test my proposal algorithm to find the shortest path in OSMnx, and get results ? if yes, what are the modules that i should modify, and where can i add my contribution in OSMnx?
Thank you very much for your help
Regards
Great article Geoff!
I have some questions:
1- How can I convert the graph metrics and stats to a geopandas frame? Basic and extended stats?
2- How can I get the graph metrics within a specific MGRS grid? It’s possible to get the general metrics from a bbox, but what about a specific MGRS grid, 100×100 meters grid? Can I retrieve this information from an MGRS grid id?
Thank you in advance.
Regards.
EqualStreetNames Bern. Oder die Geschlechterverteilung der Strassennamen in meiner Heimatstadt. – habi.gna.ch says:Hello Mr. Geoff,
I am a urban designer in shenzhen, and I am interesting in your OSMnx tools to analyse street networks.
When I use two differcnt method to calculate a same place area, and got two results. These two results not in inconformity with area I download from administrative boundary jison(correct and reshape).
method 1
place = “黄埔区”
gdf = ox.geocode_to_gdf(place)
area = ox.project_gdf(gdf).unary_union.area
G = ox.graph_from_place(place, network_type=”drive”)
result:482347181.26265496
method 2
G = ox.graph_from_place(‘黄埔区’, network_type=’drive’)
G_proj = ox.project_graph(G)
nodes_proj = ox.graph_to_gdfs(G_proj, edges=False)
graph_area_m = nodes_proj.unary_union.convex_hull.area
graph_area_m
result:565770922.8681948
When I use qgis import this area from administrative boundary, its 484042855 m2.
In general, for this area comes from ‘drive’, so area is smaller than the area from administrative boundary.
So ,I want to know if these two methods use different area, and I found method 1 area result suit for old city such as guangzhou ,and has large deviation in shenzhen. Method 2 is suit for shenzhen , smaller than administrative boundary(I think it reasonable), but has great difference with old city as guangzhou.
Thank you very much for your help
Regards
Hello Geoff,
Thanks for this article. It is very interesting. I would like to generate and analyse the network traffic of a city in SUMO. Please how can I save the map that I have retrieved using osmnx to use it in SUMO.
Thank you very much for your help.
Regards.
Hello Geoff,
I am always getting this issue with the most recent version of all the Python packages:
SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)
MaxRetryError: HTTPSConnectionPool(host=’nominatim.openstreetmap.org’, port=443): Max retries exceeded with url: /search?format=json&polygon_geojson=1&dedupe=0&limit=50&q=Berkeley%2C+California (Caused by SSLError(SSLCertVerificationError(1, ‘[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)’)))
Thank you!
Francois
This is one of my favourite libraries – really good work. I especially love the auto simplification and removal of excess nodes when using ‘graph_from’. If you are still making improvements it would be useful if this same simplification can be applied when using features_from or if alternatively if non-paths can be collected from the API as graphs. Ran into a little problem with ski trails :)
[…] We mentioned that spatial data of any nature can be analyzed: social data, natural objects or artificial constructions. Let’s look even deeper into the source code. From the figures we can see that distance calculation is performed on routes built with regard to roads, which is reasonable, because usually we don’t fly to bars by helicopters, but walk. Therefore, the ‘distance’ analysis includes the search for routes on the road graph, using the one from OSM. That is, the algorithm searches for a route on the following abstractions (we relied on the following article, highly recommended — OSMnx: Python for Street Networks): […]
Proximity Analysis to Find the Nearest Bar Using Python | by Mikhail Sarafanov | Oct, 2023 - Cash AI says:[…] We mentioned that spatial data of any nature can be analyzed: social data, natural objects or artificial constructions. Let’s look even deeper into the source code. From the figures we can see that distance calculation is performed on routes built with regard to roads, which is reasonable, because usually we don’t fly to bars by helicopters, but walk. Therefore, the ‘distance’ analysis includes the search for routes on the road graph, using the one from OSM. That is, the algorithm searches for a route on the following abstractions (we relied on the following article, highly recommended — OSMnx: Python for Street Networks): […]
[…] We mentioned that spatial data of any nature can be analyzed: social data, natural objects or artificial constructions. Let’s look even deeper into the source code. From the figures we can see that distance calculation is performed on routes built with regard to roads, which is reasonable, because usually we don’t fly to bars by helicopters, but walk. Therefore, the ‘distance’ analysis includes the search for routes on the road graph, using the one from OSM. That is, the algorithm searches for a route on the following abstractions (we relied on the following article, highly recommended — OSMnx: Python for Street Networks): […]
Proximity Analysis to Find the Nearest Bar Using Python | by Mikhail Sarafanov | Oct, 2023 - Earth Prime News Media says:[…] We mentioned that spatial data of any nature can be analyzed: social data, natural objects or artificial constructions. Let’s look even deeper into the source code. From the figures we can see that distance calculation is performed on routes built with regard to roads, which is reasonable, because usually we don’t fly to bars by helicopters, but walk. Therefore, the ‘distance’ analysis includes the search for routes on the road graph, using the one from OSM. That is, the algorithm searches for a route on the following abstractions (we relied on the following article, highly recommended — OSMnx: Python for Street Networks): […]
Proximity Evaluation to Discover the Nearest Bar Utilizing Python | by Mikhail Sarafanov | Oct, 2023 – Endelivered says:[…] We talked about that spatial knowledge of any nature could be analyzed: social knowledge, pure objects or synthetic constructions. Let’s look even deeper into the supply code. From the figures we will see that distance calculation is carried out on routes constructed with regard to roads, which is cheap, as a result of normally we don’t fly to bars by helicopters, however stroll. Due to this fact, the ‘distance’ evaluation contains the seek for routes on the street graph, utilizing the one from OSM. That’s, the algorithm searches for a route on the next abstractions (we relied on the next article, extremely beneficial — OSMnx: Python for Avenue Networks): […]
Proximity Evaluation to Discover the Nearest Bar Utilizing Python | by Mikhail Sarafanov | Oct, 2023 – Comand Osia says:[…] We talked about that spatial information of any nature will be analyzed: social information, pure objects or synthetic constructions. Let’s look even deeper into the supply code. From the figures we will see that distance calculation is carried out on routes constructed with regard to roads, which is affordable, as a result of often we don’t fly to bars by helicopters, however stroll. Due to this fact, the ‘distance’ evaluation consists of the seek for routes on the highway graph, utilizing the one from OSM. That’s, the algorithm searches for a route on the next abstractions (we relied on the next article, extremely advisable — OSMnx: Python for Street Networks): […]
Proximity Evaluation to Discover the Nearest Bar Utilizing Python | by Mikhail Sarafanov | Oct, 2023 - says:[…] We talked about that spatial information of any nature could be analyzed: social information, pure objects or synthetic constructions. Let’s look even deeper into the supply code. From the figures we will see that distance calculation is carried out on routes constructed with regard to roads, which is cheap, as a result of normally we don’t fly to bars by helicopters, however stroll. Subsequently, the ‘distance’ evaluation contains the seek for routes on the highway graph, utilizing the one from OSM. That’s, the algorithm searches for a route on the next abstractions (we relied on the next article, extremely beneficial — OSMnx: Python for Road Networks): […]
[…] We mentioned that spatial data of any nature can be analyzed: social data, natural objects or artificial constructions. Let’s look even deeper into the source code. From the figures we can see that distance calculation is performed on routes built with regard to roads, which is reasonable, because usually we don’t fly to bars by helicopters, but walk. Therefore, the ‘distance’ analysis includes the search for routes on the road graph, using the one from OSM. That is, the algorithm searches for a route on the following abstractions (we relied on the following article, highly recommended — OSMnx: Python for Street Networks): […]