def roads_type_folium(file_graphml, road_type, place_country): # load grapho grafo = ox.load_graphml(file_graphml) # ox.plot_graph(grafo) # adding a new column of edge color to gdf of the graph edges gdf_edges = ox.graph_to_gdfs(grafo, nodes=False, fill_edge_geometry=True) gdf_nodes = ox.graph_to_gdfs(grafo, edges=False) # road_type = road_type.replace(' ', '') # road_type = ['motorway', 'motorway_link', 'secondary', 'primary', 'tertiary', 'residential', 'unclassified' # , 'trunk', 'trunk_link', 'tertiary_link', 'secondary_link'] # road = gdf_edges[(gdf_edges.highway.isin( list(road_type.split (",")) ))] # ox.get_edge_colors_by_attr.... # make a dictionary for ech color # road_color_dict = { # "secondary": "red", # "primary": "green", # "tertiary": "blue", # "motorway_link": "yellow", # "motorway": "black", # "trunk": "orange", # "trunk_link": "orange", # "residential": "orange", # "unclassified": "brown", # "tertiary_link": "orange", # "secondary_link": "orange", # "service": "orange" # } road_color_dict = { "secondary": "lightgrey", "primary": "lightgrey", "tertiary": "lightgrey", "motorway_link": "black", "motorway": "black", "trunk": "black", "trunk_link": "black", "residential": "lightgrey", "unclassified": "lightgrey", "tertiary_link": "lightgrey", "secondary_link": "lightgrey", "service": "lightgrey" } points = [] # prepare a base_map ########################################################### gdf_edges_copy = gdf_edges gdf_edges_copy = gdf_edges_copy['highway'].str.replace(r"\(.*\)", "") gdf_edges.highway = gdf_edges_copy gen_network = gdf_edges[gdf_edges.highway.isin(road_type)] # gen_network = gdf_edges[(gdf_edges.highway.isin([road_type.split(",")[0]]))] # gen_network = gdf_edges[(gdf_edges.highway.isin(["secondary"]))] # calculate Average Latitude and average Longitude for i in range(len(gen_network)): gen_poly = ox.make_folium_polyline(edge=gen_network.iloc[i], edge_color="black", edge_width=1, edge_opacity=1, popup_attribute=None) points.append(gen_poly.locations) gen_poly_unlisted = list(chain.from_iterable(points)) ave_lat = sum(p[0] for p in gen_poly_unlisted) / len(gen_poly_unlisted) ave_lon = sum(p[1] for p in gen_poly_unlisted) / len(gen_poly_unlisted) my_map = folium.Map(location=[ave_lat, ave_lon], zoom_start=13, tiles='cartodbpositron') # tiles='cartodbpositron' # my_map.save("Catania_motorway.html") # my_map.save("Catania_partial.html") ################################################################################## # add nodes to my_map for i in range(len(gdf_nodes)): folium.CircleMarker( location=[gdf_nodes.y.iloc[i], gdf_nodes.x.iloc[i]], popup=gdf_nodes.osmid.iloc[i], radius=4, color="red", fill=True, fill_color="yellow", fill_opacity=0.6).add_to(my_map) # add edges # road_type = list(road_type.split(",")) for road in road_type: print(road) if road in road_color_dict.keys(): print("yes") color_road = road_color_dict.get(road) motorway = gdf_edges[(gdf_edges.highway.isin([road]))] points = [] if len(motorway) != 0: for i in range(len(motorway)): motorway_poly = ox.make_folium_polyline(edge=motorway.iloc[i], edge_color="black", edge_width=1, edge_opacity=1, popup_attribute=None) points.append(motorway_poly.locations) folium.PolyLine(points, color=color_road, weight=2, opacity=1).add_to(my_map) name_place_country = re.sub('[/," ",:]', '_', place_country) # roadtype = ' '.join([str(elem) for elem in road_type]) # roads = re.sub('[/," ",:]', '_', roadtype) # my_map.save(name_place_country + "_" + "partial" + ".html") # my_map.save("Catania_partial.html") my_map.save("Fisciano_partial.html") return my_map
# make a dictionary for ech color road_color_dict = { "secondary": "red", "primary": "green", "tertiary": "blue", "motorway_link": "yellow", "motorway": "black" } points = [] # prepare a base_map ########################################################### gen_network = gdf_edges[(gdf_edges.highway.isin(["motorway"]))] for i in range(len(gen_network)): gen_poly = ox.make_folium_polyline(edge=gen_network.iloc[i], edge_color="black", edge_width=1, edge_opacity=1, popup_attribute=None) points.append(gen_poly.locations) gen_poly_unlisted = list(chain.from_iterable(points)) ave_lat = sum(p[0] for p in gen_poly_unlisted) / len(gen_poly_unlisted) ave_lon = sum(p[1] for p in gen_poly_unlisted) / len(gen_poly_unlisted) my_map = folium.Map(location=[ave_lat, ave_lon], zoom_start=12) ################################################################################## # add nodes to my_map for i in range(len(gdf_nodes)): folium.CircleMarker(location=[gdf_nodes.y.iloc[i], gdf_nodes.x.iloc[i]], popup=gdf_nodes.osmid.iloc[i], radius=5,
def graphRoute(route, ax=None): """check route displaying a graph""" G = nx.MultiDiGraph() G.graph['crs'] = {'init': 'epsg:4326'} G.graph['name'] = "local network" colorL = [ 'black', 'blue', 'red', 'green', 'brown', 'orange', 'purple', 'magenta', 'olive', 'maroon', 'steelblue', 'midnightblue', 'darkslategrey', 'crimson', 'teal', 'darkolivegreen' ] colorL = colorL + colorL for i, g in route.iterrows(): G.add_node(i, pos=(g[['x', 'y']]), x=g['x'], y=g['y'], key=0, potential=g['potential'], active=g['active'], n=g['occupancy']) for k, g in route.groupby("agent"): if k == 0: continue idx = list(g.index) if len(idx) < 2: continue pair_idx = [(i, j) for i, j in zip(idx[:-1], idx[1:])] for i, j in pair_idx: g1, g2 = route.loc[i], route.loc[j] i1, i2 = g1['geohash'], g2['geohash'] dist = math.hypot(g1['x'] - g2['x'], g1['y'] - g2['y']) G.add_edge(i, j, key=k, origin=i1, destination=i2, length=dist, width=1, speed=1, color=colorL[k]) G = ox.project_graph(G) colorL = [cm.get_cmap('plasma')(x) for x in np.linspace(0, 1, 6)] nc = ['blue' if G.nodes()[x]['active'] else 'red' for x in G.nodes()] nbins = min(20, len(set(route['potential']))) cmap = matplotlib.cm.get_cmap('plasma') max_pot = np.percentile(route['potential'], 95) nc = [cmap(x['potential'] / max_pot) for i, x in G.nodes(data=True)] # nc = ox.get_node_colors_by_attr(G,'potential',cmap='plasma',num_bins=nbins-2) ns = [20. * x['n'] for i, x in G.nodes(data=True)] # ec = ox.get_edge_colors_by_attr(G, attr='length') ec = [o['color'] for u, v, k, o in G.edges(data=True, keys=True)] # if len(ec) == 0: return plt.subplots(1,1) ew = [200. * o['length'] for u, v, k, o in G.edges(data=True, keys=True)] pos, lab = {}, {} for i, x in G.nodes(data=True): pos[i] = [x['lon'], x['lat']] for i, x in G.nodes(data=True): lab[i] = i # nx.draw_networkx_edge_labels(G,pos,edge_colors=ec) if ax == None: fig, ax = plt.subplots(1, 1) fig.set_size_inches(10, 6) # nx.draw(G,pos,node_color=nc,node_size=ns,edge_color=ec,edge_cmap=plt.cm.Reds) nx.draw_networkx_nodes(G, pos, node_color=nc, node_size=ns, alpha=0.1, ax=ax) # nx.draw_networkx_labels(G,pos,lab,font_size=8,ax=ax,alpha=0.3) nx.draw_networkx_edges(G, pos, width=ew, alpha=0.5, edge_color=ec, ax=ax, edge_cmap=plt.cm.Reds) ax.set_axis_off() ax.set_xlim(np.percentile(route['x'], [1, 99])) ax.set_ylim(np.percentile(route['y'], [1, 99])) return ax if False: gdf_edges = ox.graph_to_gdfs(G, nodes=False, fill_edge_geometry=True) graph_map = ox.plot_graph_folium(G, tiles='stamenterrain', edge_color=ec, edge_width=2) origin_node = list(G.nodes())[0] destination_node = list(G.nodes())[-1] route = nx.shortest_path(G, origin_node, destination_node) route_map = ox.plot_route_folium(G, route) graph_map.save(baseDir + "www/gis/folium.html") ox.make_folium_polyline(gdf_edges, ew, ew, popup_attribute=None) plot_graph_folium(gdf_edges, graph_map=None, popup_attribute=None, tiles='cartodbpositron', zoom=1, fit_bounds=True, edge_width=5, edge_opacity=1) return fig, ax
def _plot_graph_folium(self, G, graph_map=None, popup_attribute=None, tiles='cartodbpositron', zoom=1, fit_bounds=True, edge_color='#333333', edge_width=5, edge_opacity=1): """ Plot a graph on an interactive folium web map. Note that anything larger than a small city can take a long time to plot and create a large web map file that is very slow to load as JavaScript. Parameters ---------- G : networkx multidigraph graph_map : folium.folium.Map if not None, plot the graph on this preexisting folium map object popup_attribute : string edge attribute to display in a pop-up when an edge is clicked tiles : string name of a folium tileset zoom : int initial zoom level for the map fit_bounds : bool if True, fit the map to the boundaries of the route's edges edge_color : string color of the edge lines edge_width : numeric width of the edge lines edge_opacity : numeric opacity of the edge lines Returns ------- graph_map : folium.folium.Map """ # check if we were able to import folium successfully if not folium: raise ImportError( 'The folium package must be installed to use this optional feature.' ) # create gdf of the graph edges gdf_edges = osmnx.graph_to_gdfs(G, nodes=False, fill_edge_geometry=True) # get graph centroid x, y = gdf_edges.unary_union.centroid.xy graph_centroid = (y[0], x[0]) # create the folium web map if one wasn't passed-in if graph_map is None: graph_map = folium.Map(location=graph_centroid, zoom_start=zoom, tiles=tiles) # add each graph edge to the map for index, row in gdf_edges.iterrows(): pl = osmnx.make_folium_polyline(edge=row, edge_color=edge_color[index], edge_width=edge_width, edge_opacity=edge_opacity, popup_attribute=popup_attribute) pl.add_to(graph_map) # if fit_bounds is True, fit the map to the bounds of the route by passing # list of lat-lng points as [southwest, northeast] if fit_bounds: tb = gdf_edges.total_bounds bounds = [(tb[1], tb[0]), (tb[3], tb[2])] graph_map.fit_bounds(bounds) return graph_map
def roads_type_folium(file_graphml, road_type, place_country): # load grapho grafo = ox.load_graphml(file_graphml) # adding a new column of edge color to gdf of the graph edges gdf_edges = ox.graph_to_gdfs(grafo, nodes=False, fill_edge_geometry=True) gdf_nodes = ox.graph_to_gdfs(grafo, edges=False) road_type = road_type.replace(' ', '') # road = gdf_edges[(gdf_edges.highway.isin( list(road_type.split (",")) ))] # make a dictionary for ech color road_color_dict = { "secondary": "red", "primary": "green", "tertiary": "blue", "motorway_link": "yellow", "motorway": "black", "residential": "orange", "unclassified": "brown", "living_street": "orange", "trunk": "black", "trunk_link": "black" } # 'living_street', # ['tertiary', 'unclassified'], # ['tertiary', 'residential', 'unclassified'], # ['secondary', 'unclassified'] # ['secondary', 'tertiary'] # ['tertiary', 'residential'] # ['secondary', 'residential'] # ['residential', 'unclassified'] # "trunk points = [] # prepare a base_map ########################################################### gen_network = gdf_edges[(gdf_edges.highway.isin([road_type.split(",")[0]]))] # gen_network = gdf_edges[(gdf_edges.highway.isin(["secondary"]))] for i in range(len(gen_network)): gen_poly = ox.make_folium_polyline(edge=gen_network.iloc[i], edge_color="black", edge_width=1, edge_opacity=1, popup_attribute=None) points.append(gen_poly.locations) gen_poly_unlisted = list(chain.from_iterable(points)) ave_lat = sum(p[0] for p in gen_poly_unlisted) / len(gen_poly_unlisted) ave_lon = sum(p[1] for p in gen_poly_unlisted) / len(gen_poly_unlisted) my_map = folium.Map(location=[ave_lat, ave_lon], zoom_start=12, tiles='cartodbpositron') # tiles='cartodbpositron' # my_map.save("Catania_motorway.html") ################################################################################## # add nodes to my_map for i in range(len(gdf_nodes)): folium.CircleMarker(location=[gdf_nodes.y.iloc[i], gdf_nodes.x.iloc[i]], popup=gdf_nodes.osmid.iloc[i], radius=5, color="red", fill=True, fill_color="yellow", fill_opacity=0.6).add_to(my_map) # add edges road_type = list(road_type.split(",")) for road in road_type: if road in road_color_dict.keys(): color_road = road_color_dict.get(road) motorway = gdf_edges[(gdf_edges.highway.isin([road]))] points = [] for i in range(len(motorway)): motorway_poly = ox.make_folium_polyline(edge=motorway.iloc[i], edge_color="black", edge_width=1, edge_opacity=1, popup_attribute=None) points.append(motorway_poly.locations) folium.PolyLine(points, color=color_road, weight=3, opacity=1).add_to(my_map) name_place_country = re.sub('[/," ",:]', '_', place_country) roadtype = ' '.join([str(elem) for elem in road_type]) roads = re.sub('[/," ",:]', '_', roadtype) my_map.save(name_place_country + "_" + roads + ".html") return my_map