69 lines
2.3 KiB
Python
69 lines
2.3 KiB
Python
# -*- coding: UTF-8 -*-
|
|
import osmnx as ox
|
|
import networkx as nx
|
|
import geopy.distance
|
|
import datetime
|
|
import matplotlib.pyplot as plt
|
|
import math
|
|
|
|
ox.config(use_cache=True, log_console=False)
|
|
|
|
partenza= 'Via leonardo da vinci, Luino Varese'
|
|
arrivo='varese'
|
|
orig_point = ox.geocode(partenza)
|
|
dest_point = ox.geocode(arrivo)
|
|
|
|
center_lat = (orig_point[0] + dest_point[0]) / 2
|
|
center_long = (orig_point[1] + dest_point[1]) / 2
|
|
center_point = (center_lat, center_long)
|
|
|
|
|
|
# Calcola la distanza geodesica tra le coordinate utilizzando geopy
|
|
#distance = geopy.distance.geodesic(orig_point, dest_point).meters-5000
|
|
distance = ox.distance.great_circle(orig_point[0], orig_point[1], dest_point[0], dest_point[1])
|
|
|
|
|
|
print(f'partenza da {partenza}, coordinate = {orig_point}( {orig_point[0],orig_point[1]} ')
|
|
print(f'arrivo a {arrivo}, coordinate = {dest_point}( {dest_point[0],dest_point[1]} )')
|
|
print(f'punto centrale, coordinate = {center_point}')
|
|
|
|
|
|
G = ox.graph_from_point(center_point, dist=distance, network_type='drive')
|
|
# impute missing edge speeds then calculate edge travel times
|
|
G = ox.add_edge_speeds(G)
|
|
G = ox.add_edge_travel_times(G)
|
|
|
|
orig_node = ox.nearest_nodes(G, Y=orig_point[0], X=orig_point[1])
|
|
dest_node = ox.nearest_nodes(G, Y=dest_point[0], X=dest_point[1])
|
|
|
|
route = nx.shortest_path(G, orig_node, dest_node, weight='length')
|
|
|
|
# Ottenere gli attributi della route
|
|
route_attributes = ox.utils_graph.get_route_edge_attributes(G, route, 'length')
|
|
|
|
# Sommare le lunghezze dei singoli segmenti della route
|
|
route1_length = sum(route_attributes)
|
|
|
|
# Ottenere gli attributi di tempo di percorrenza della route
|
|
route_times = ox.utils_graph.get_route_edge_attributes(G, route, 'travel_time')
|
|
|
|
# Sommare i tempi di percorrenza dei singoli segmenti della route
|
|
route1_time = int(sum(route_times))
|
|
|
|
print('Route 1 takes', route1_time, 'seconds.')
|
|
|
|
delta_time = datetime.timedelta(seconds=route1_time)
|
|
formatted_time = str(delta_time)
|
|
|
|
print('Route 1 is', route1_length, 'meters and takes', formatted_time, 'seconds.')
|
|
|
|
fig, ax = ox.plot_graph_route(G, route, route_linewidth=6, node_size=0, bgcolor='k',show=False, close=False)
|
|
|
|
|
|
|
|
padding=1
|
|
ax.scatter(G.nodes[orig_node]['x'], G.nodes[orig_node]['y'], c='lime', s=200, label=partenza, marker='x')
|
|
ax.scatter(G.nodes[dest_node]['x'], G.nodes[dest_node]['y'], c='red', s=200, label=arrivo, marker='x')
|
|
plt.show()
|
|
|