def test_routing_folium(): G = ox.graph_from_address(address=address, dist=500, dist_type="bbox", network_type="bike") # give each node a random elevation then calculate edge grades randm = np.random.random(size=len(G)) elevs = {n: e for n, e in zip(G.nodes(), randm)} nx.set_node_attributes(G, name="elevation", values=elevs) G = ox.add_edge_grades(G, add_absolute=True) # give each edge speed and travel time attributes G = ox.add_edge_speeds(G) G = ox.add_edge_travel_times(G) orig_node = list(G.nodes())[5] dest_node = list(G.nodes())[-5] orig_pt = (G.nodes[orig_node]["y"], G.nodes[orig_node]["x"]) dest_pt = (G.nodes[dest_node]["y"], G.nodes[dest_node]["x"]) route = nx.shortest_path(G, orig_node, dest_node, weight="travel_time") attributes = ox.utils_graph.get_route_edge_attributes( G, route, "travel_time") fig, ax = ox.plot_graph_route(G, route, save=True, filename="route", file_format="png") fig, ax = ox.plot_graph_route( G, route, origin_point=orig_pt, destination_point=dest_pt, save=True, filename="route", file_format="png", ) # test multiple routes fig, ax = ox.plot_graph_routes(G, [route, route]) # test folium gm = ox.plot_graph_folium(G, popup_attribute="name") rm = ox.plot_route_folium(G, route) # test calling folium plotters with FeatureGroup instead of Map, and extra kwargs fg = folium.FeatureGroup(name="legend name", show=True) gm = ox.plot_graph_folium(G, graph_map=fg) assert isinstance(gm, folium.FeatureGroup) rm = ox.plot_route_folium(G, route, route_color="g", route_map=fg, tooltip="x") assert isinstance(rm, folium.FeatureGroup)
def test_routing(): G = ox.graph_from_address(address=address, dist=500, dist_type="bbox", network_type="bike") # give each edge speed and travel time attributes G = ox.add_edge_speeds(G) G = ox.add_edge_speeds(G, hwy_speeds={"motorway": 100}) G = ox.add_edge_travel_times(G) orig_x = np.array([-122.404771]) dest_x = np.array([-122.401429]) orig_y = np.array([37.794302]) dest_y = np.array([37.794987]) orig_node = ox.distance.nearest_nodes(G, orig_x, orig_y)[0] dest_node = ox.distance.nearest_nodes(G, dest_x, dest_y)[0] route = ox.shortest_path(G, orig_node, dest_node, weight="travel_time") attributes = ox.utils_graph.get_route_edge_attributes(G, route) attributes = ox.utils_graph.get_route_edge_attributes( G, route, "travel_time") fig, ax = ox.plot_graph_route(G, route, save=True) # test multiple origins-destinations n = 5 nodes = np.array(G.nodes) origs = np.random.choice(nodes, size=n, replace=True) dests = np.random.choice(nodes, size=n, replace=True) paths1 = ox.shortest_path(G, origs, dests, weight="length", cpus=1) paths2 = ox.shortest_path(G, origs, dests, weight="length", cpus=2) paths3 = ox.shortest_path(G, origs, dests, weight="length", cpus=None) assert paths1 == paths2 == paths3 # test k shortest paths routes = ox.k_shortest_paths(G, orig_node, dest_node, k=2, weight="travel_time") fig, ax = ox.plot_graph_routes(G, list(routes)) # test folium with keyword arguments to pass to folium.PolyLine gm = ox.plot_graph_folium(G, popup_attribute="name", color="#333333", weight=5, opacity=0.7) rm = ox.plot_route_folium(G, route, color="#cc0000", weight=5, opacity=0.7) # test calling folium plotters with FeatureGroup instead of Map, and extra kwargs fg = folium.FeatureGroup(name="legend name", show=True) gm = ox.plot_graph_folium(G, graph_map=fg) assert isinstance(gm, folium.FeatureGroup) rm = ox.plot_route_folium(G, route, route_map=fg, tooltip="x") assert isinstance(rm, folium.FeatureGroup)
def test_routing(): G = ox.graph_from_address(address=address, dist=500, dist_type="bbox", network_type="bike") # give each node a random elevation then calculate edge grades randm = np.random.random(size=len(G)) elevs = {n: e for n, e in zip(G.nodes(), randm)} nx.set_node_attributes(G, name="elevation", values=elevs) G = ox.add_edge_grades(G, add_absolute=True) # give each edge speed and travel time attributes G = ox.add_edge_speeds(G) G = ox.add_edge_speeds(G, hwy_speeds={"motorway": 100}) G = ox.add_edge_travel_times(G) orig_node = list(G.nodes())[5] dest_node = list(G.nodes())[-5] orig_pt = (G.nodes[orig_node]["y"], G.nodes[orig_node]["x"]) dest_pt = (G.nodes[dest_node]["y"], G.nodes[dest_node]["x"]) route = ox.shortest_path(G, orig_node, dest_node, weight="travel_time") attributes = ox.utils_graph.get_route_edge_attributes(G, route) attributes = ox.utils_graph.get_route_edge_attributes( G, route, "travel_time") fig, ax = ox.plot_graph_route(G, route, save=True) fig, ax = ox.plot_graph_route(G, route, save=True) # test multiple routes routes = ox.k_shortest_paths(G, orig_node, dest_node, k=2, weight="travel_time") fig, ax = ox.plot_graph_routes(G, list(routes)) # test folium with keyword arguments to pass to folium.PolyLine gm = ox.plot_graph_folium(G, popup_attribute="name", color="#333333", weight=5, opacity=0.7) rm = ox.plot_route_folium(G, route, color="#cc0000", weight=5, opacity=0.7) # test calling folium plotters with FeatureGroup instead of Map, and extra kwargs fg = folium.FeatureGroup(name="legend name", show=True) gm = ox.plot_graph_folium(G, graph_map=fg) assert isinstance(gm, folium.FeatureGroup) rm = ox.plot_route_folium(G, route, route_map=fg, tooltip="x") assert isinstance(rm, folium.FeatureGroup)
def test_routing_folium(): import networkx as nx with httmock.HTTMock( get_mock_response_content('overpass-response-3.json.gz')): G = ox.graph_from_address('398 N. Sicily Pl., Chandler, Arizona', distance=800, network_type='drive') origin = (33.307792, -111.894940) destination = (33.312994, -111.894998) origin_node = ox.get_nearest_node(G, origin) destination_node = ox.get_nearest_node(G, destination) route = nx.shortest_path(G, origin_node, destination_node) attributes = ox.get_route_edge_attributes(G, route, 'length') fig, ax = ox.plot_graph_route(G, route, save=True, filename='route', file_format='png') fig, ax = ox.plot_graph_route(G, route, origin_point=origin, destination_point=destination, save=True, filename='route', file_format='png') graph_map = ox.plot_graph_folium(G, popup_attribute='name') route_map = ox.plot_route_folium(G, route)
def run(self, start, end, ele_mode, cost_percentage): start = ox.geocode(start) target = ox.geocode(end) graph_origin_file = "data/Amherst_city_graph.pkl" graph_project_file = "data/Amherst_city_graph_projected.pkl" # "Amherst_city_graph_projected.pkl" graph_project, graph_orig = controller_obj.read_map_data(False, graph_origin_file, graph_project_file) source = ox.get_nearest_node(graph_orig, (start)) destination = ox.get_nearest_node(graph_orig, (target)) shortest_path_length = self.get_ground_truth_shorest_length(graph_orig, source, destination) # self.get_total_length(graph_projection, shortest_path) overhead = cost_percentage allowed_cost = ((100.0 + overhead) * shortest_path_length) / 100.0 elevation_mode = ele_mode route2 = self.get_dijkstra_evelation_shorest_perentage_route(graph_orig, source, destination, allowed_cost, elevation_mode=elevation_mode) x = ox.plot_route_folium(graph_orig, route2, route_color='green') folium.Marker(location=start, icon=folium.Icon(color='red')).add_to(x) folium.Marker(location=target, icon=folium.Icon(color='blue')).add_to(x) filepath = "output/example.html" x.save(filepath)
def bikin_rute(lat_input,long_input,lat_center,long_center,lat_output,long_output): titik_awal = [lat_input, long_input] titik_tujuan = [lat_output, long_output] bandung = (lat_center, long_center) G = ox.graph_from_point(bandung, distance=600) nodes, _ = ox.graph_to_gdfs(G) #ambil attribut edges pada G edges = ox.graph_to_gdfs(G, nodes=False, edges=True, node_geometry=False, fill_edge_geometry=False) #kasi nilai random antara 1-10 pada G['weight'] edges['weight'] = np.random.randint(1,10, size=len(edges)) #campur ke G G = ox.gdfs_to_graph(nodes,edges) #deklarasi tree untuk mendeteksi closest nodes pada titik awal dan tujuan tree = KDTree(nodes[['y', 'x']], metric='euclidean') awal = tree.query([titik_awal], k=1, return_distance=False)[0] tujuan = tree.query([titik_tujuan], k=1, return_distance=False)[0] #dapat nodes terdekat closest_node_to_awal = nodes.iloc[awal].index.values[0] closest_node_to_tujuan = nodes.iloc[tujuan].index.values[0] route = nx.dijkstra_path(G, closest_node_to_awal,closest_node_to_tujuan,weight='weight') basemap = ox.plot_route_folium(G, route, route_color='green') folium.Marker(location=titik_awal,icon=folium.Icon(color='red')).add_to(basemap) folium.Marker(location=titik_tujuan,icon=folium.Icon(color='green')).add_to(basemap) basemap.save(outfile= "C:/xampp/htdocs/js/flask2/templates/djikstra.html")
def test_routing_folium(): # calculate shortest path and plot as static image and leaflet web map import networkx as nx G = ox.graph_from_address('398 N. Sicily Pl., Chandler, Arizona', distance=800, network_type='drive') origin = (33.307792, -111.894940) destination = (33.312994, -111.894998) origin_node = ox.get_nearest_node(G, origin) destination_node = ox.get_nearest_node(G, destination, method='euclidean') route = nx.shortest_path(G, origin_node, destination_node) attributes = ox.get_route_edge_attributes(G, route, 'length') fig, ax = ox.plot_graph_route(G, route, save=True, filename='route', file_format='png') fig, ax = ox.plot_graph_route(G, route, origin_point=origin, destination_point=destination, save=True, filename='route', file_format='png') graph_map = ox.plot_graph_folium(G, popup_attribute='name') route_map = ox.plot_route_folium(G, route)
def test_routing_folium(): import networkx as nx G = ox.graph_from_address('N. Sicily Pl., Chandler, Arizona', distance=800, network_type='drive') origin = (33.307792, -111.894940) destination = (33.312994, -111.894998) origin_node = ox.get_nearest_node(G, origin) destination_node = ox.get_nearest_node(G, destination) route = nx.shortest_path(G, origin_node, destination_node) fig, ax = ox.plot_graph_route(G, route, save=True, filename='route', file_format='png') fig, ax = ox.plot_graph_route(G, route, origin_point=origin, destination_point=destination, save=True, filename='route', file_format='png') graph_map = ox.plot_graph_folium(G, popup_attribute='name') route_map = ox.plot_route_folium(G, route)
def mapRoute(points): #Reference: https://stackoverflow.com/questions/60578408/is-it-possible-to-draw-paths-in-folium ox.config(log_console=True, use_cache=True) G_walk = ox.graph_from_place('Vancouver, British Columbia, Canada', network_type='walk') nodes = [] routes = [] for index, row in points.iterrows(): nodes.append(ox.get_nearest_node(G_walk, (row['lat'], row['lon']))) if index > 0: routes.append( nx.shortest_path(G_walk, nodes[index - 1], nodes[index], weight='length')) for route in routes: route_map = ox.plot_route_folium(G_walk, route) return route_map
def form_valid(self, form): # obj = self.get_object() ox.config(log_console=True, use_cache=True) G = ox.graph_from_place('Sievierodonetsk, UA', network_type='drive') a = (form.instance.point_a, form.instance.point_b) b = (form.instance.point_c, form.instance.point_d) orig_node = ox.get_nearest_node(G, a, method='euclidean') dest_node = ox.get_nearest_node(G, b, method='euclidean') route_direct = nx.shortest_path(G, orig_node, dest_node, weight='length') route_return = nx.shortest_path(G, dest_node, orig_node, weight='length') route_map = ox.plot_route_folium(G, route_direct, route_color='green', route_width=5, route_opacity=0.5, tiles='openstreetmap', popup_attribute='length') route_map = ox.plot_route_folium(G, route_return, route_color='blue', route_width=5, route_opacity=0.5, route_map=route_map, popup_attribute='length') folium.Marker(location=(G.node[orig_node]['y'], G.node[orig_node]['x']), icon=folium.Icon(color='green', prefix='fa', icon='flag')).add_to(route_map) folium.Marker( location=(G.node[dest_node]['y'], G.node[dest_node]['x']), icon=folium.Icon(color='blue', prefix='fa', icon='flag-checkered')).add_to(route_map) generated_route = route_map.get_root().render() form.instance.route_view = generated_route return super().form_valid(form)
def bikin_rute_multiple(lat_center,long_center,lat_in1,lng_in1,lat_in2,lng_in2,lat_in3,lng_in3): titik_1 = [lat_in1, lng_in1] titik_2 = [lat_in2, lng_in2] titik_3 = [lat_in3, lng_in3] #titik_1 = [-6.921169, 107.601442] #titik_2 = [-6.928275, 107.604579] #titik_3 = [-6.922519, 107.607146] bandung = (lat_center, long_center) G = ox.graph_from_point(bandung, distance=600) nodes, _ = ox.graph_to_gdfs(G) #ambil attribut edges pada G edges = ox.graph_to_gdfs(G, nodes=False, edges=True, node_geometry=False, fill_edge_geometry=False) #kasi nilai random antara 1-10 pada G['weight'] edges['weight'] = np.random.randint(1,10, size=len(edges)) #campur ke G G = ox.gdfs_to_graph(nodes,edges) #deklarasi tree untuk mendeteksi closest nodes pada titik awal dan tujuan tree = KDTree(nodes[['y', 'x']], metric='euclidean') point1 = tree.query([titik_1], k=1, return_distance=False)[0] point2 = tree.query([titik_2], k=1, return_distance=False)[0] point3 = tree.query([titik_3], k=1, return_distance=False)[0] #dapat nodes terdekat closest_node_to_1 = nodes.iloc[point1].index.values[0] closest_node_to_2 = nodes.iloc[point2].index.values[0] closest_node_to_3 = nodes.iloc[point3].index.values[0] route1 = nx.dijkstra_path(G, closest_node_to_1,closest_node_to_2,weight='weight') route2 = nx.dijkstra_path(G, closest_node_to_2,closest_node_to_3,weight='weight') tooltip = 'Click me!' basemap = ox.plot_route_folium(G, route1, route_color='red') basemap2 = ox.plot_route_folium(G, route2, route_color='orange',route_map = basemap) folium.Marker(location=titik_1,popup='<i>titik 1 </i>', icon=folium.Icon(color='red')).add_to(basemap2) folium.Marker(location=titik_2,popup='<i>titik 2 </i>',icon=folium.Icon(color='orange')).add_to(basemap2) folium.Marker(location=titik_3,popup='<i>titik 3 </i>',icon=folium.Icon(color='blue')).add_to(basemap2) basemap2.save(outfile= "C:/xampp/htdocs/js/flask2/templates/multiple_djikstra.html")
def drawRoutes(self, graph, routes, colors): print("MapWebView: draw routes.") fmap = None for i in range(len(routes)): fmap = ox.plot_route_folium(graph, routes[i], route_map=fmap, route_color=colors[i%len(colors)]+"AA") fmap.save(TEMP_PATH+"map.html") #self.load(QUrl("file:///"+TEMP_PATH+"map.html")) self.load(QUrl.fromLocalFile(TEMP_PATH+"map.html"))
def drawRoutes(self, graph, routes, colors): fmap = None for i in range(len(routes)): fmap = ox.plot_route_folium(graph, routes[i], route_map=fmap, route_color=colors[i % len(colors)] + "AA") fmap.save("map.html") # Display html self.load("map.html")
def find_paths(source, target, m): node1 = ox.geo_utils.get_nearest_node(G, source, method='haversine', return_dist=False) node2 = ox.geo_utils.get_nearest_node(G, target, method='haversine', return_dist=False) route = nx.shortest_path(G, node1, node2) print(route) m = ox.plot_route_folium(G, route, route_color='green') folium.Marker(location=source, icon=folium.Icon(color='red')).add_to(m) folium.Marker(location=target, icon=folium.Icon(color='red')).add_to(m) return m
def plot_html(self, source_X, source_Y, sink_X, sink_Y, route, mode): start = (source_X, source_Y) target = (sink_X, sink_Y) graph_origin_file = "data/Amherst_city_graph.pkl" graph_project_file = "data/Amherst_city_graph_projected.pkl" # "Amherst_city_graph_projected.pkl" graph_project, graph_orig = self.read_map_data(False, graph_origin_file, graph_project_file) x = ox.plot_route_folium(graph_orig, route, route_color='green') folium.Marker(location=start, icon=folium.Icon(color='red')).add_to(x) folium.Marker(location=target, icon=folium.Icon(color='blue')).add_to(x) filepath = "data/" + mode + ".html" x.save(filepath)
def planRoute(bnb, amenities_list, choice): ''' Reference: https://stackoverflow.com/questions/60578408/is-it-possible-to-draw-paths-in-folium ''' ox.config(log_console=True, use_cache=True) if choice == 1: G_walk = ox.graph_from_place('Vancouver, British Columbia, Canada', network_type='walk') elif choice == 2: G_walk = ox.graph_from_place('Vancouver, British Columbia, Canada', network_type='bike') else: G_walk = ox.graph_from_place('Vancouver, British Columbia, Canada', network_type='drive') orig_node = ox.get_nearest_node(G_walk, (bnb.iloc[0]['lat'], bnb.iloc[0]['lon'])) dest_node = orig_node nodes = [] routes = [] for index, row in amenities_list.iterrows(): nodes.append(ox.get_nearest_node(G_walk, (row['lat'], row['lon']))) if index == 0: routes.append( nx.shortest_path(G_walk, orig_node, nodes[index], weight='length')) elif (index == len(amenities_list.index) - 1): routes.append( nx.shortest_path(G_walk, nodes[index], dest_node, weight='length')) else: routes.append( nx.shortest_path(G_walk, nodes[index - 1], nodes[index], weight='length')) for route in routes: route_map = ox.plot_route_folium(G_walk, route) return route_map
def mergeNplot(optimal_path, locations): lat = lon = 0 # Finding the center of all locations, it's purpose is for generating the map for location in locations: lat += location[0] lon += location[1] lat = lat / len(locations) lon = lon / len(locations) mid_point = (lat, lon) # Calculating the distace from each location to mid_point distances = [distance.distance(x, mid_point).meters for x in locations] dist = max(distances) + 200 #Generating the graph graph = ox.graph_from_point(mid_point, dist) graph_map = ox.plot_graph_folium(graph, popup_attribute='name', edge_width=0) # Generating the route according to the optimal order of the locations routes = [] for i in range(len(optimal_path) - 1): l1 = locations[optimal_path[i]] l2 = locations[optimal_path[i + 1]] orig_node = ox.get_nearest_node(graph, l1) dest_node = ox.get_nearest_node(graph, l2) route = nx.shortest_path(graph, source=orig_node, target=dest_node, weight='length') route_graph_map = ox.plot_route_folium(graph, route, route_map=graph_map) routes.append(route) # Markers addition on the places locations. i = 0 for location in optimal_path: folium.Marker(location=locations[location], popup=i, icon=folium.Icon(color='blue')).add_to(graph_map) i += 1 graph_map.save('tsp_graph.html')
def draw_route(G, route, zoom = 16): if len(G) >= 1000: print(f"The graph has {len(G)} which is a lot, we will use basic faster folium instead") m = ox.plot_route_folium(G = G, route = route) return m center_osmid = ox.stats.extended_stats(G,ecc=True)['center'][0] G_gdfs = ox.graph_to_gdfs(G) nodes_frame = G_gdfs[0] ways_frame = G_gdfs[1] center_node = nodes_frame.loc[center_osmid] location = (center_node['y'], center_node['x']) m = lf.Map(center = location, zoom = zoom) start_node = nodes_frame.loc[route[0]] end_node = nodes_frame.loc[route[len(route)-1]] start_xy = (start_node['y'], start_node['x']) end_xy = (end_node['y'], end_node['x']) marker = lf.Marker(location = start_xy, draggable = False) m.add_layer(marker) marker = lf.Marker(location = end_xy, draggable = False) m.add_layer(marker) for u, v in zip(route[0:], route[1:]): try: x, y = (ways_frame.query(f'u == {u} and v == {v}').to_dict('list')['geometry'])[0].coords.xy except: x, y = (ways_frame.query(f'u == {v} and v == {u}').to_dict('list')['geometry'])[0].coords.xy points = map(list, [*zip([*y],[*x])]) ant_path = lf.AntPath( locations = [*points], dash_array=[1, 10], delay=1000, color='red', pulse_color='black' ) m.add_layer(ant_path) return m
def mapa_interactivo(self, g, rutas, nombre_ruta): """ crea un mapa interactivo con folium con las rutas que se le den g --> grafo creado del punto de ubicacion rutas --> diccionario con las rutas de los usuarios retorna : Folium.Map() con las rutas que se esecifiquen""" m = folium.Map(location=[-12.070874, -77.02552], zoom_start=15, tiles='Stamen Terrain') colors = ['blue', 'blue', 'green', 'green', 'brown'] for ruta in rutas: if ruta != nombre_ruta: color = np.random.choice(colors) else: color = 'red' temp = ox.plot_route_folium(g, rutas[ruta], route_map=m, route_color=color) return m
def test_routing_folium(): # calculate shortest path and plot as static image and leaflet web map import networkx as nx G = ox.graph_from_address('398 N. Sicily Pl., Chandler, Arizona', distance=800, network_type='drive') origin = (33.307792, -111.894940) destination = (33.312994, -111.894998) origin_node = ox.get_nearest_node(G, origin) destination_node = ox.get_nearest_node(G, destination, method='euclidean') route = nx.shortest_path(G, origin_node, destination_node) attributes = ox.get_route_edge_attributes(G, route, 'length') fig, ax = ox.plot_graph_route(G, route, save=True, filename='route', file_format='png') fig, ax = ox.plot_graph_route(G, route, origin_point=origin, destination_point=destination, save=True, filename='route', file_format='png') # test multiple routes fig, ax = ox.plot_graph_routes(G, [route, route]) graph_map = ox.plot_graph_folium(G, popup_attribute='name') route_map = ox.plot_route_folium(G, route)
def test_routing_folium(): # calculate shortest path and plot as static image and leaflet web map G = ox.graph_from_address(address=address, dist=500, dist_type="bbox", network_type="bike") # give each node a random elevation then calculate edge grades randm = np.random.random(size=len(G.nodes())) elevs = {n: e for n, e in zip(G.nodes(), randm)} nx.set_node_attributes(G, name="elevation", values=elevs) G = ox.add_edge_grades(G, add_absolute=True) orig_node = list(G.nodes())[5] dest_node = list(G.nodes())[-5] orig_pt = (G.nodes[orig_node]["y"], G.nodes[orig_node]["x"]) dest_pt = (G.nodes[dest_node]["y"], G.nodes[dest_node]["x"]) route = nx.shortest_path(G, orig_node, dest_node) attributes = ox.utils_graph.get_route_edge_attributes(G, route, "length") fig, ax = ox.plot_graph_route(G, route, save=True, filename="route", file_format="png") fig, ax = ox.plot_graph_route( G, route, origin_point=orig_pt, destination_point=dest_pt, save=True, filename="route", file_format="png", ) # test multiple routes fig, ax = ox.plot_graph_routes(G, [route, route]) graph_map = ox.plot_graph_folium(G, popup_attribute="name") route_map = ox.plot_route_folium(G, route)
def generate_route(start_address, end_address): # read in api key api_file = open("api_key.txt", "r") api_key = api_file.read() api_file.close() url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&" # get distance google maps finds for path res = requests.get(url + "origins=" + start_address + "&destinations=" + end_address + "&key=" + api_key) google_dist = res.json()['rows'][0]['elements'][0]['distance']['value'] start_geocode = ox.geocode(start_address) end_geocode = ox.geocode(end_address) # get bounding box coordinates N, S, E, W = calc_box_points(start_geocode, end_geocode) print(f"\n{Fore.BLUE}Creating osm graph...{Style.RESET_ALL}") # generate multi digraph from osm data start = time.time() osm_graph = ox.graph_from_bbox(north=N, south=S, east=E, west=W, truncate_by_edge=True) end = time.time() print( f"{Fore.GREEN}Osm graph created in {round(end - start, 2)} seconds!{Style.RESET_ALL}\n" ) # get nodes from osm_graph nodes, _ = ox.graph_to_gdfs(osm_graph) # convert nodes into KDTree, uses euclidean distance by default kd_tree = KDTree(nodes[['y', 'x']]) # use tree structure to quickly find nearest node start_index = kd_tree.query([start_geocode], return_distance=False)[0] end_index = kd_tree.query([end_geocode], return_distance=False)[0] start_node = nodes.iloc[start_index].index.values[0] end_node = nodes.iloc[end_index].index.values[0] # display route on graph print(f"{Fore.BLUE}Calculating route...{Style.RESET_ALL}") start = time.time() route, distance = dijkstras(osm_graph, start_node, end_node) end = time.time() print( f"{Fore.GREEN}Route calculated in {round((end - start) * 1000, 2)} ms!{Style.RESET_ALL}" ) print() print(f"Distance: {distance}m") print(f"Google distance: {google_dist}") # calculate accuracy of pathing accuracy = 100 - abs(((distance - google_dist) / (google_dist)) * 100) if accuracy >= 90.0: print(f"{Fore.GREEN}Accuracy: {round(accuracy, 2)}% {Style.RESET_ALL}") else: print(f"{Fore.RED}Accuracy: {round(accuracy, 2)}% {Style.RESET_ALL}") print() # overlay route onto map and set icons to show start and end route_map = ox.plot_route_folium(osm_graph, route) folium.Marker(location=start_geocode, icon=folium.Icon(color='red')).add_to(route_map) folium.Marker(location=end_geocode, icon=folium.Icon(color='green')).add_to(route_map) route_map.save('templates/route.html')
import osmnx as ox, network as nx ox.config(log_console=True, use_cache=True) # download the street network for Piedmont, CA G = ox.graph_from_place('Piedmont, California, USA', network_type='drive') # plot the street network with folium graph_map = ox.plot_graph_folium(G, popup_attribute='name', edge_width=2) # save as html file then display map as an iframe filepath = 'data/graph.html' graph_map.save(filepath) IFrame(filepath, width=600, height=500) # use networkx to calculate the shortest path between two nodes origin_node = list(G.nodes())[0] destination_node = list(G.nodes())[-1] route = nx.shortest_path(G, origin_node, destination_node) # plot the route with folium route_map = ox.plot_route_folium(G, route) # save as html file then display map as an iframe# save filepath = 'data/route.html' route_map.save(filepath) IFrame(filepath, width=600, height=500)
c='green', s=100) plt.show() # In[34]: route = nx.shortest_path(G, closest_node_to_lib, closest_node_to_museum) fig, ax = ox.plot_graph_route(G, route, fig_height=10, fig_width=10, show=False, close=False, edge_color='black', orig_dest_node_color='green', route_color='green') ax.scatter(library[1], library[0], c='red', s=100) ax.scatter(museum[1], museum[0], c='blue', s=100) plt.show() # In[35]: m = ox.plot_route_folium(G, route, route_color='green') folium.Marker(location=library, icon=folium.Icon(color='red')).add_to(m) folium.Marker(location=museum, icon=folium.Icon(color='blue')).add_to(m) m
def submit(self): city = str(self.ui.comboCity.currentText()) month = str(self.ui.comboMonth.currentText()) day = str(self.ui.comboDay.currentText()) city1, month1 = get_filters(city, month) global df, df5, df6, gender_mean, female_mean, male_mean, user_subs, user_cust, user global ut_subs, ut_cust, ut_subs_fem, ut_subs_male, ut_cust_fem, ut_cust_male df, df5 = load_data(city1, month1, day) try: now = datetime.datetime.now() df['age'] = now.year - df['Birth Year'] except: df['age'] = 0 pass try: female_mean = df[df['Gender'] == 'Female'].groupby( 'Start Station').mean() female_mean['count'] = df[df['Gender'] == 'Female'].groupby( 'Start Station')['Id'].count() female_mean.drop(columns=[ 'latitude_start', 'longitude_start', 'latitude_end', 'longitude_end' ], inplace=True) male_mean = df[df['Gender'] == 'Male'].groupby( 'Start Station').mean() male_mean['count'] = df[df['Gender'] == 'Male'].groupby( 'Start Station')['Id'].count() gender_mean = male_mean.merge(female_mean, how='outer', left_index=True, right_index=True, suffixes=(' male', ' female')) gender_mean['count total'] = gender_mean[ 'count female'] + gender_mean['count male'] gender_mean['female percent'] = (gender_mean['count female'] / gender_mean['count total']) * 100 except: pass try: user_subs = df[df['User Type'] == 'Subscriber'].groupby( 'Start Station').mean() user_subs['count'] = df[df['User Type'] == 'Subscriber'].groupby( 'Start Station')['Id'].count() user_cust = df[df['User Type'] == 'Customer'].groupby( 'Start Station').mean() user_cust['count'] = df[df['User Type'] == 'Customer'].groupby( 'Start Station')['Id'].count() user_cust.drop(columns=[ 'latitude_start', 'longitude_start', 'latitude_end', 'longitude_end' ], inplace=True) user = user_subs.merge(user_cust, how='outer', left_index=True, right_index=True, suffixes=(' subs', ' cust')) user.dropna(subset=['latitude_start'], inplace=True) user['count subs'] = user['count subs'].fillna(0) user['count cust'] = user['count cust'].fillna(0) user['count total'] = user['count subs'] + user['count cust'] user['subs percent'] = (user['count subs'] / user['count total']) * 100 except: pass # Statistics commonMonth, commonDay, commonHour = time_stats(df, city1, month1, day) commonStartStation, commonEndStation, G, route, dataFr, distRec = station_stats( df) ttt, ttm = trip_duration_stats(df) ut_subs, ut_cust, ut_subs_fem, ut_subs_male, ut_cust_fem, ut_cust_male = user_stats( df) df6 = dfStats(df, df5, dataFr) tstat = [] tstat.append('Statistics on the most frequent times of travel') tstat.append('The Most Common Month : ' + str(commonMonth)) tstat.append('The Most Common Day : ' + str(commonDay)) tstat.append('The Most Common Hour : ' + str(commonHour)) tstat.append('\nStatistics on the most popular stations and trip') tstat.append('The Most Common Used Start Station : ' + str(commonStartStation)) tstat.append('The Most Common Used End Station : ' + str(commonEndStation)) tstat.append('\nStatistics on the most popular combination stations') tstat.append('The Most Common Combination of Start-End Station : ' + str(dataFr['Start Station'].iloc[0]) + ' and ' + str(dataFr['End Station'].iloc[0])) tstat.append( 'The Most Common Combination of Start-End Station Track (km): ' + str(distRec[0])) tstat.append( 'The Most Common Combination of Start-End Station Lineal Distance (km): ' + str(dataFr['Dist_lin_km'].iloc[0])) tstat.append('\nStatistics on the total and average trip duration') tstat.append('The total travel time : ' + str(ttt)) tstat.append('The mean travel time : ' + str(ttm)) tstat.append('\nDisplays statistics on bikeshare users and gender') tstat.append('The counts of user types "Subscriber" : ' + str(len(ut_subs))) tstat.append('The counts of user types "Customer" : ' + str(len(ut_cust))) try: tstat.append( 'The counts of user types "Subscriber" and Gender "Female": ' + str(len(ut_subs_fem))) tstat.append( 'The counts of user types "Subscriber" and Gender "Male": ' + str(len(ut_subs_male))) tstat.append( 'The counts of user types "Customer" and Gender "Female": ' + str(len(ut_cust_fem))) tstat.append( 'The counts of user types "Customer" and Gender "Male": ' + str(len(ut_cust_male))) except: pass try: tstat.append( '\nDisplay earliest, most recent, and most common year of birth' ) tstat.append('The earliest year of birt: ' + str(int(df['Birth Year'].min()))) tstat.append('The most recent year of birt: ' + str(int(df['Birth Year'].max()))) tstat.append('The most common year of birt: ' + str(int(df['Birth Year'].mode()))) except: pass self.ui.textEdit.setText("\n".join(tstat)) # Route Map graph_map = ox.plot_graph_folium(G, popup_attribute='name', edge_width=2, edge_color="#85d3de", zoom=8) try: route_graph_map = ox.plot_route_folium(G, route, route_map=graph_map, popup_attribute='length', zoom=8) except: route_graph_map = graph_map locations = df6[['latitude', 'longitude']] locationlist = locations.values.tolist() for point in range(0, len(df6)): Marker(locationlist[point], popup=df6[['Station', 'name' ]].iloc[point].values).add_to(route_graph_map) filepath = 'CommonStation_ShortestPath.html' route_graph_map.save(filepath) w = self.ui.webEngineView_1 w.resize(740, 540) self.url = QtCore.QUrl.fromLocalFile(str(pathname) + '/' + filepath) w.load(self.url) w.show() ##Bike Stations maps = Map([df5['latitude'].mean(), df5['longitude'].mean()], zoom_start=10, control_scale=True, tiles="OpenStreetMap") locations2 = df5[['latitude', 'longitude']] locationlist2 = locations2.values.tolist() group2 = FeatureGroup(name="Bike Stations") for point in range(0, len(locationlist2)): Marker(locationlist2[point], popup=df5[['Station', 'latitude', 'longitude']].iloc[point].values).add_to(group2) group2.add_to(maps) LayerControl().add_to(maps) data = io.BytesIO() maps.save(data, close_file=False) m = self.ui.webEngineView_2 m.setHtml(data.getvalue().decode()) m.resize(740, 540) maps.save("BikeStations.html") m.show() maps.save(data, close_file=True) # initial map tab maps = Map([df5['latitude'].mean(), df5['longitude'].mean()], zoom_start=10, control_scale=True, tiles="OpenStreetMap") LayerControl().add_to(maps) data = io.BytesIO() maps.save(data, close_file=False) m = self.ui.webEngineView_3 m.setHtml(data.getvalue().decode()) m.resize(740, 520) m.show() maps.save(data, close_file=True) try: # initial Graphics self.figure.clear() labels = 'Male', 'Female' sizes = [ len(df[df['Gender'] == 'Male']), len(df[df['Gender'] == 'Female']) ] explode = (0, 0.1) ax1 = self.figure.add_subplot(111) ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', startangle=90) ax1.axis('equal') self.canvas.draw() self.show except: pass # setting value to progress bar for i in range(101): time.sleep(0.04) self.ui.progressBar.setValue(i)
def get_map(self, start_lat, start_long, end_lat, end_long, chosen_weight): print( "Coordinates", start_lat, start_long, end_lat, end_long, ) print("weight", chosen_weight) place = 'Amherst' place_query = { 'city': 'Amherst', 'state': 'Massachusetts', 'country': 'USA' } G = ox.graph_from_place(place_query, network_type='drive') G = ox.add_node_elevations( G, api_key='AIzaSyB9DBYn2sdIznFbmBg4DHOTl54soDBkx2E') G = ox.add_edge_grades(G) edge_grades = [ data['grade_abs'] for u, v, k, data in ox.get_undirected(G).edges(keys=True, data=True) ] avg_grade = np.mean(edge_grades) #print('Average street grade in {} is {:.1f}%'.format(place, avg_grade*100)) if chosen_weight == 0: choice = 'length' elif chosen_weight == 1: choice = 'minimum' elif chosen_weight == 2: choice = 'impedence' med_grade = np.median(edge_grades) #print('Median street grade in {} is {:.1f}%'.format(place, med_grade*100)) # project the street network to UTM G_proj = ox.project_graph(G) # get one color for each node, by elevation, then plot the network #nc = ox.get_node_colors_by_attr(G_proj, 'elevation', cmap='plasma', num_bins=20) #fig, ax = ox.plot_graph(G_proj, fig_height=6, node_color=nc, node_size=12, node_zorder=2, edge_color='#dddddd') # get a color for each edge, by grade, then plot the network #ec = ox.get_edge_colors_by_attr(G_proj, 'grade_abs', cmap='plasma', num_bins=10) #fig, ax = ox.plot_graph(G_proj, fig_height=6, edge_color=ec, edge_linewidth=0.8, node_size=0) # select an origin and destination node and a bounding box around them origin = ox.get_nearest_node(G, (start_lat, start_long)) destination = ox.get_nearest_node(G, (end_lat, end_long)) bbox = ox.bbox_from_point( ((start_lat + end_lat) / 2, (start_long + end_long) / 2), distance=5000, project_utm=True) for u, v, k, data in G_proj.edges(keys=True, data=True): data['impedance'] = self.impedance(data['length'], data['grade_abs']) data['rise'] = data['length'] * data['grade'] #weight_choice = {'easy' : 'length', 'median' : 'minimum', 'hard' : 'impedance'} routef = nx.shortest_path(G_proj, source=origin, target=destination, weight=choice) route_map = ox.plot_route_folium(G, routef) p1 = [start_lat, start_long] p2 = [end_lat, end_long] folium.Marker(location=p1, icon=folium.Icon(color='green')).add_to(route_map) folium.Marker(location=p2, icon=folium.Icon(color='red')).add_to(route_map) print("------------------4321") result = self.print_route_stats(routef, G_proj) filepath = 'routeff.html' route_map.save(filepath) IFrame(filepath, width=600, height=500) return result
def seeshortestway(x1, x2): #loc1 = ox.geocode(x1) #loc2 = ox.geocode(x2) place1 = gmaps.geocode(x1) lat1 = place1[0]['geometry']['location']['lat'] lng1 = place1[0]['geometry']['location']['lng'] place2 = gmaps.geocode(x2) lat2 = place2[0]['geometry']['location']['lat'] lng2 = place2[0]['geometry']['location']['lng'] loc1 = (lat1, lng1) loc2 = (lat2, lng2) #KD트리를 이용하면 최단거리를 쉽고 효율적으로 찾아준다. tree = KDTree(nodes[['y', 'x']], metric='euclidean') loc1_idx = tree.query([loc1], k=1, return_distance=False)[0] loc2_idx = tree.query([loc2], k=1, return_distance=False)[0] closest_node_to_loc1 = nodes.iloc[loc1_idx].index.values[0] closest_node_to_loc2 = nodes.iloc[loc2_idx].index.values[0] route = nx.shortest_path(G, closest_node_to_loc1, closest_node_to_loc2, weight='length') onlygodoroute = nx.shortest_path(G, closest_node_to_loc1, closest_node_to_loc2, weight='grade_abs') impedanceroute = nx.shortest_path(G, closest_node_to_loc1, closest_node_to_loc2, weight='impedance') #distance=nx.shortest_path_length(G, closest_node_to_loc1,closest_node_to_loc2) graderoute = [] impedance = [] for i in range(len(onlygodoroute)): lng = G.node[onlygodoroute[i]]['x'] lat = G.node[onlygodoroute[i]]['y'] b = [lat, lng] graderoute.append(b) for i in range(len(impedanceroute)): lng = G.node[impedanceroute[i]]['x'] lat = G.node[impedanceroute[i]]['y'] b = [lat, lng] impedance.append(b) m = ox.plot_route_folium(G, route, route_color='navy', tiles='stamen toner') antpath = plugins.AntPath(locations=graderoute, color='purple') antpath.add_to(m) antpath = plugins.AntPath(locations=impedance, color='red') antpath.add_to(m) #folium.PolyLine(graderoute, color="purple", weight=4).add_to(m) #folium.PolyLine(impedance, color="red", weight=4).add_to(m) kw = {'prefix': 'fa', 'color': 'green', 'icon': 'arrow-up'} ka = {'prefix': 'fa', 'color': 'blue', 'icon': 'arrow-up'} icon1 = folium.Icon(angle=45, **kw) folium.Marker(location=loc1, icon=icon1, popup=x1, tooltip='출발').add_to(m) icon2 = folium.Icon(angle=180, **ka) folium.Marker(location=loc2, icon=icon2, popup=x2, tooltip='도착').add_to(m) #lium.Marker(location=loc1, # icon=folium.Icon(color='red'), popup=x1, tooltip='출발').add_to(m) #folium.Marker(location=loc2, #icon=folium.Icon(color='blue'),popup=x2, tooltip='도착').add_to(m) dobo = 4 add = [] for i in range(len(route) - 1): lng1 = G.node[route[i]]['x'] lat1 = G.node[route[i]]['y'] lng2 = G.node[route[i + 1]]['x'] lat2 = G.node[route[i + 1]]['y'] result = GeoUtil.get_harversion_distance(lng1, lat1, lng2, lat2) add.append(result) noroundkm = sum(add) km = round(noroundkm, 1) noroundminute = (km / dobo) * 60 minute = round(noroundminute, 1) print('거리는', km, 'KM 이며, ', '시간은', minute, '분 걸립니다.') return m
return_dist=True) # testing algorithmn speed start_time = time.time() final = walk_astar(startosmid[0], endosmid[0]) print("--- %s seconds ---" % round((time.time() - start_time), 2)) # calculating estimated time to reach the destination taking avg human walking speed of 1.4m/s totaldist = final[1] + (startosmid[1] * 1000) + (endosmid[1] * 1000) estwalk = totaldist / (1.4 * 60) print("Time: " + str(round(estwalk)) + " minutes" + "\nDistance: " + str(round((totaldist / 1000), 2)) + " km") # plotting map to folium print(final[0]) m = ox.plot_route_folium(G_walk, final[0], route_color='#00008B', route_width=5, tiles="OpenStreetMap") m.save('templates/astar_walking.html') ''' FLASK IS HERE FLASK IS HERE FLASK IS HERE FLASK IS HERE ''' app = Flask(__name__) @app.route("/") def index(): return render_template('index.html')
endpoint, method='euclidean', return_dist=True) lrtstart = lrt_nearnode(locateStrtLrt[0])[1] lrtend = lrt_nearnode(lcoateEndLrt[0])[1] if (lrtstart == lrtend or (lrtstart == 6587709456 and lrtend == 6587709457) or (lrtstart == 6587709457 and lrtend == 6587709456)): # and (start point bus stop node is same as end point): final = walk_astar(strtpt[0], endpt[0]) # plotting map to folium m = ox.plot_route_folium( G_walk, final[0], route_color='blue', route_width=5, tiles="OpenStreetMap", popup_attribute= "There is no LRT to bring you to your destination, please walk.") m.save('templates/astaralgo_walklrtbus.html') else: reachLRT = ox.get_nearest_node(G_walk, mrtn_latlon(lrtstart), method='euclidean', return_dist=True) leaveLRT = ox.get_nearest_node(G_walk, mrtn_latlon(lrtend), method='euclidean', return_dist=True) eastlrt = 0
def drawRoute(self, graph, route, color): fmap = ox.plot_route_folium(graph, route, route_color=color) fmap.save("map.html") # Display html self.load("map.html")
destination_node = ox.get_nearest_node(G, destination) print(origin) print(destination) route = nx.shortest_path(G, origin_node, destination_node) # XXX double check if weights are taken into account. # %% ox.plot_graph_route(G, route) # %% ox.plot_route_folium(G, route, route_width=2, route_color='#AA1111') # Adapted from : https://blog.ouseful.info/2018/06/29/working-with-openstreetmap-roads-data-using-osmnx/ # %% G.is_multigraph() # %% edges = ox.graph_to_gdfs(G, nodes=False, edges=True) nodes = ox.graph_to_gdfs(G, nodes=True, edges=False) # Check columns print(edges.columns) print(nodes.columns)