Search code examples
networkxgeopandasosmnx

Can I add random nodes on edges manually in OSMNX?


I am new to OSMnx and to NetworkX packages in python.

Let's say I have the following example:

import numpy as np
import osmnx as ox
import geopandas as gpd
import networkx as nx


place_name = 'Fefan'
graph = ox.graph_from_place(place_name, network_type='drive')
graph_proj = ox.project_graph(graph)
nodes_proj= ox.graph_to_gdfs(graph_proj, nodes=True, edges=False)
ox.plot_graph(graph_proj)

As you can see, I only obtain the two nodes for this place. I guess that's how it is in OSM. Is there any way I can manually add random nodes in this graph, especially on the edges of it?

For a broader picture. I need the nodes to calculate some distance matrices between some buildings, which are not shown here.

Best,


Solution

  • You can do this in the following way.

    Import nodes and edges as geodataframes.

    import numpy as np
    import osmnx as ox
    import geopandas as gpd
    import networkx as nx
    
    
    place_name = 'Fefan'
    graph = ox.graph_from_place(place_name, network_type='drive')
    nodes= ox.graph_to_gdfs(graph, nodes=True, edges=False)
    edges= ox.graph_to_gdfs(graph, edges=True, nodes=False)
    ox.plot_graph(graph)
    

    Create a dictionary for the new nodes. I have just added one new node in this case.

    import geopandas as gpd
    from shapely.geometry import  Point
    
    my_dict = {
      '001': {
        'y': 7.367210, 
        'x': 151.838487,
        'street_count': 1
      }
    }
    

    Create a new geodataframe for the new node.

    tmp_list = []
    for item_key, item_value in my_dict.items() :
      tmp_list.append({
        'geometry' : Point(item_value['x'], item_value['y']),
        'osmid': item_key,
        'y' : item_value['y'],
          'x' : item_value['x'],
        'street_count': item_value ['street_count']
       })
    my_nodes = gpd.GeoDataFrame(tmp_list)
    

    Append new geodataframe (my_nodes) to the old geodataframe (nodes) to modify the old geodataframe and plot.

    nodes = nodes.append(my_nodes, ignore_index = True)
    graph2 = ox.graph_from_gdfs(nodes, edges)
    ox.plot_graph(graph2)
    

    enter image description here