Calculating Road distance between coordinates

47 views Asked by At

`Hi everyone, Im trying to calculate the road distance between a list of coordinates. I have succeeded to load both the nodes with the coordinates and a Graph from a the roads from the country through a .shp file. However, once I view the nodes on the map road and I try to calculate the distance through nx.shortest_path_length from NetworkX, it seems the nodes are not connected.

I assume the problem is from the Graph but I tried it also with Openstreetmaps and it happens the same. Any clue of how to solve the problem without using an API?`

import pandas as pd
import networkx as nx
import geopandas as gpd
from shapely.geometry import Point, LineString

# Read the shapefile using GeoPandas
shp = gpd.read_file('route name')

# Adjust the projection if necessary
shp = shp.to_crs(epsg=32721)

# Read the Excel file with UTM coordinates
df = pd.read_excel("route")

# Create a directed graph
G = nx.DiGraph()

# Add nodes to the graph with their attributes (numerations)
for _, row in df.iterrows():
    numeracion = row['Numeraciones']
    este = row['ESTE']
    norte = row['NORTE']
    G.add_node(numeracion, pos=(este, norte))

# Simplify road geometries
shp['simplified'] = shp['geometry'].simplify(50)  # Adjust the simplification value as needed

# Assign the nearest road to each node
for node, data in G.nodes(data=True):
    node_pos = data['pos']
    node_point = Point(node_pos[0], node_pos[1])
    min_distance = float('inf')
    nearest_road = None
    for idx, road in shp.iterrows():
        road_geom = road['simplified']
        distance_to_road = road_geom.distance(node_point)
        if distance_to_road < min_distance:
            min_distance = distance_to_road
            nearest_road = road_geom
    G.nodes[node]['nearest_road'] = nearest_road

# Calculate the road distance between each pair of nodes
for u, v in G.edges():
    u_road = G.nodes[u]['nearest_road']
    v_road = G.nodes[v]['nearest_road']
    if u_road is not None and v_road is not None:
        intersection = u_road.intersection(v_road)
        if isinstance(intersection, LineString):
            distance = intersection.length
            G[u][v]['distance'] = distance

# Create a list to store the distances between nodes
distances_data = []

# Calculate the road distance between each pair of nodes
for u, v, data in G.edges(data=True):
    if 'distance' in data:
        distance = data['distance']
        distances_data.append({'Origin_Node': u, 'Destination_Node': v, 'Distance': distance})

# Create a DataFrame with the distances data
distances_df = pd.DataFrame(distances_data)

# Print the DataFrame with distances to the console
print("Distances between nodes:")
print(distances_df)
0

There are 0 answers