def save(self, filename, data_layers): """data_layers should be a dict of format {name: 'Airplane', color: 'blue', trackpoints: [[lat, lon]]}""" map = folium.Map(location=[38.58, -99.09], zoom_start=3, tiles="Mapbox Bright") for layer in data_layers: fgp = folium.FeatureGroup(name=layer['name']) if layer['name'] == 'Airplane': attr = { 'font-weight': 'bold', 'font-size': '20', 'opacity': 0.5 } plane_line = folium.PolyLine(layer['trackpoints'], color=layer['color'], weight=1, opacity=0.5) plane_line1 = plugins.PolyLineTextPath( plane_line, '\u2708 ', repeat=True, offset=8, attributes=attr) fgp.add_child(plane_line) fgp.add_child(plane_line1) else: fgp.add_child( folium.PolyLine(layer['trackpoints'], color=layer['color'], weight=2.5, opacity=0.5)) map.add_child(fgp) map.add_child(folium.LayerControl()) map.save(filename)
def test_polyline_text_path(): m = folium.Map([20., 0.], zoom_start=3) wind_locations = [[59.355600, -31.99219], [55.178870, -42.89062], [47.754100, -43.94531], [38.272690, -37.96875], [27.059130, -41.13281], [16.299050, -36.56250], [8.4071700, -30.23437], [1.0546300, -22.50000], [-8.754790, -18.28125], [-21.61658, -20.03906], [-31.35364, -24.25781], [-39.90974, -30.93750], [-43.83453, -41.13281], [-47.75410, -49.92187], [-50.95843, -54.14062], [-55.97380, -56.60156]] wind_line = folium.PolyLine(wind_locations, weight=15, color='#8EE9FF') attr = {'fill': '#007DEF', 'font-weight': 'bold', 'font-size': '24'} wind_textpath = plugins.PolyLineTextPath(wind_line, ') ', repeat=True, offset=7, attributes=attr) m.add_child(wind_line) m.add_child(wind_textpath) m._repr_html_() out = m._parent.render() # We verify that the script import is present. script = '<script src="https://rawcdn.githack.com/makinacorpus/Leaflet.TextPath/leaflet0.8-dev/leaflet.textpath.js"></script>' # noqa assert script in out # We verify that the script part is correct. tmpl = Template(""" {{this.polyline.get_name()}}.setText("{{this.text}}", { repeat: {{'true' if this.repeat else 'false'}}, center: {{'true' if this.center else 'false'}}, below: {{'true' if this.below else 'false'}}, offset: {{this.offset}}, orientation: {{this.orientation}}, attributes: {{this.attributes}} }); """) # noqa assert tmpl.render(this=wind_textpath) in out
def test_polyline_text_path(): m = folium.Map([20., 0.], zoom_start=3) wind_locations = [[59.355600, -31.99219], [55.178870, -42.89062], [47.754100, -43.94531], [38.272690, -37.96875], [27.059130, -41.13281], [16.299050, -36.56250], [8.4071700, -30.23437], [1.0546300, -22.50000], [-8.754790, -18.28125], [-21.61658, -20.03906], [-31.35364, -24.25781], [-39.90974, -30.93750], [-43.83453, -41.13281], [-47.75410, -49.92187], [-50.95843, -54.14062], [-55.97380, -56.60156]] wind_line = folium.PolyLine(wind_locations, weight=15, color='#8EE9FF') attr = {'fill': '#007DEF', 'font-weight': 'bold', 'font-size': '24'} wind_textpath = plugins.PolyLineTextPath(wind_line, ') ', repeat=True, offset=7, attributes=attr) m.add_child(wind_line) m.add_child(wind_textpath) out = normalize(m._parent.render()) # We verify that the script import is present. script = '<script src="https://cdn.jsdelivr.net/npm/[email protected]/leaflet.textpath.min.js"></script>' # noqa assert script in out # We verify that the script part is correct. tmpl = Template(""" {{ this.polyline.get_name() }}.setText( "{{this.text}}", {{ this.options|tojson }} ); """) expected = normalize(tmpl.render(this=wind_textpath)) assert expected in out
def map_trips(feed, trip_ids, color_palette=cs.COLORS_SET2, *, include_stops=True): """ Return a Folium map showing the given trips and (optionally) their stops. Parameters ---------- feed : Feed trip_ids : list IDs of trips in ``feed.trips`` color_palette : list Palette to use to color the routes. If more routes than colors, then colors will be recycled. include_stops : boolean If ``True``, then include stops in the map Returns ------- dictionary A Folium Map depicting the shapes of the trips. If ``include_stops``, then include the stops for each trip. Notes ------ - Requires Folium """ import folium as fl import folium.plugins as fp # Get routes slice and convert to dictionary trips = (feed.trips.loc[lambda x: x['trip_id'].isin(trip_ids)].fillna( 'n/a').to_dict(orient='records')) # Create colors n = len(trips) colors = [color_palette[i % len(color_palette)] for i in range(n)] # Initialize map my_map = fl.Map(tiles='cartodbpositron') # Collect route bounding boxes to set map zoom later bboxes = [] # Create a feature group for each route and add it to the map for i, trip in enumerate(trips): collection = feed.trip_to_geojson(trip_id=trip['trip_id'], include_stops=include_stops) group = fl.FeatureGroup(name='Trip ' + trip['trip_id']) color = colors[i] for f in collection['features']: prop = f['properties'] # Add stop if f['geometry']['type'] == 'Point': lon, lat = f['geometry']['coordinates'] fl.CircleMarker(location=[lat, lon], radius=8, fill=True, color=color, weight=1, popup=fl.Popup( hp.make_html(prop))).add_to(group) # Add path else: # Path prop['color'] = color path = fl.GeoJson( f, name=trip, style_function=lambda x: {'color': x['properties']['color']}, ) path.add_child(fl.Popup(hp.make_html(prop))) path.add_to(group) # Direction arrows, assuming, as GTFS does, that # trip direction equals LineString direction fp.PolyLineTextPath(path, ' \u27A4 ', repeat=True, offset=5.5, attributes={ 'fill': color, 'font-size': '18' }).add_to(group) bboxes.append(sg.box(*sg.shape(f['geometry']).bounds)) group.add_to(my_map) fl.LayerControl().add_to(my_map) # Fit map to bounds bounds = so.unary_union(bboxes).bounds bounds2 = [bounds[1::-1], bounds[3:1:-1]] # Folium expects this ordering my_map.fit_bounds(bounds2) return my_map
# City -> Airport -> Aircraft for city in cities: folium.Marker(city.coordinate[::-1], popup='<i>{}</i>'.format(city.airports), tooltip=city.name).add_to(m) for airport in city.airports: folium.Marker(airport.coordinate[::-1], popup='<i>{}</i>'.format(airport), tooltip=airport.name, icon=folium.Icon(color='red', icon='info-sign')).add_to(m) # Airline attr = { 'text': '\u2708' + ' ' * 16, 'repeat': True, 'offset': 8, 'font_size': 8, } for path in airline: line = folium.PolyLine( [path[i].coordinate[::-1] for i in range(len(path))], weight=0.5, ).add_to(m) plugins.PolyLineTextPath(line, **attr).add_to(m) m.save(html_file)
m = folium.Map([30., 0.], zoom_start=3) wind_locations = [[59.3556, -31.99219], [55.17887, -42.89062], [47.7541, -43.94531], [38.27269, -37.96875], [27.05913, -41.13281], [16.29905, -36.5625], [8.40717, -30.23437], [1.05463, -22.5], [-8.75479, -18.28125], [-21.61658, -20.03906], [-31.35364, -24.25781], [-39.90974, -30.9375], [-43.83453, -41.13281], [-47.7541, -49.92187], [-50.95843, -54.14062], [-55.9738, -56.60156]] wind_line = folium.PolyLine(wind_locations, weight=15, color='#8EE9FF').add_to(m) attr = {'fill': '#007DEF', 'font-weight': 'bold', 'font-size': '24'} plugins.PolyLineTextPath(wind_line, ") ", repeat=True, offset=7, attributes=attr).add_to(m) danger_line = folium.PolyLine([[-40.311, -31.952], [-12.086, -18.727]], weight=10, color='orange', opacity=0.8).add_to(m) attr = {'fill': 'red'} plugins.PolyLineTextPath(danger_line, "\u25BA", repeat=True, offset=6, attributes=attr).add_to(m) plane_line = folium.PolyLine(
def create_geoplot(states_nostrategy, states_reload, states_target, strategy_updated): """ Helper function to visualize the data from MDP and strategy on an OpenStreetMap. Uses geodata of the street network stored as a graph in 'nyc.graphml' file. """ # Load NYC Geodata path = os.path.abspath("nyc.graphml") G = nx.MultiDiGraph(nx.read_graphml(path)) for _, _, data in G.edges(data=True, keys=False): data['speed_mean'] = float(data['speed_mean']) data['speed_sd'] = float(data['speed_sd']) data['time_mean'] = float(data['time_mean']) data['time_sd'] = float(data['time_sd']) data['energy_levels'] = ast.literal_eval(data['energy_levels']) for _, data in G.nodes(data=True): data['reload'] = ast.literal_eval(data['reload']) data['lat'] = float(data['lat']) data['lon'] = float(data['lon']) # Create baseline map with edges nodes_all = {} for node in G.nodes.data(): name = str(node[0]) point = [node[1]['lat'], node[1]['lon']] nodes_all[name] = point global_lat = [] global_lon = [] for name, point in nodes_all.items(): global_lat.append(point[0]) global_lon.append(point[1]) min_point = [min(global_lat), min(global_lon)] max_point = [max(global_lat), max(global_lon)] m = folium.Map(zoom_start=1, tiles='cartodbpositron') m.fit_bounds([min_point, max_point]) for edge in G.edges: points = [(G.nodes[edge[0]]['lat'], G.nodes[edge[0]]['lon']), (G.nodes[edge[1]]['lat'], G.nodes[edge[1]]['lon'])] folium.PolyLine(locations=points, color='gray', weight=2, opacity=0.8).add_to(m) for key, value in strategy_updated.items(): color = '#2f2f2f' for energy, end_state in value.items(): points = [(G.nodes[key]['lat'], G.nodes[key]['lon']), (G.nodes[end_state]['lat'], G.nodes[end_state]['lon'])] line = folium.PolyLine(locations=points, color=color, tooltip=str(energy), weight=1.5).add_to(m) attr = {'fill': color, 'font-size': '12'} plugins.PolyLineTextPath(line, '\u25BA', repeat=False, center=True, offset=3.5, attributes=attr).add_to(m) folium.CircleMarker( location=[G.nodes[key]['lat'], G.nodes[key]['lon']], radius=2, color=color, fill=True).add_to(m) # Add reload states, target states, and states with no prescribed action nodes_reload = {} nodes_target = {} nodes_nostrategy = {} for node in G.nodes.data(): if node[0] in states_reload: name = str(node[0]) point = [node[1]['lat'], node[1]['lon']] nodes_reload[name] = point if node[0] in states_target: name = str(node[0]) point = [node[1]['lat'], node[1]['lon']] nodes_target[name] = point if node[0] in states_nostrategy: name = str(node[0]) point = [node[1]['lat'], node[1]['lon']] nodes_nostrategy[name] = point # Plot reload states for node_name, node_point in nodes_reload.items(): folium.CircleMarker(location=[node_point[0], node_point[1]], radius=3, popup='reload state', color="#22af4b", fill_color="#22af4b", fill_opacity=1, fill=True).add_to(m) # Plot target nodes for node_name, node_point in nodes_target.items(): folium.CircleMarker(location=[node_point[0], node_point[1]], radius=3, popup='target state', color="#0f89ca", fill_color="#0f89ca", fill_opacity=1, fill=True).add_to(m) # Plot no strategy nodes for node_name, node_point in nodes_nostrategy.items(): folium.CircleMarker(location=[node_point[0], node_point[1]], radius=3, popup='no guarantees state', color='red', fill_color='red', fill_opacity=1, fill=True).add_to(m) return m
def map_trips( feed: "Feed", trip_ids: Iterable[str], color_palette: list[str] = cs.COLORS_SET2, *, include_stops: bool = False, include_arrows: bool = False, ): """ Return a Folium map showing the given trips and (optionally) their stops. If any of the given trip IDs are not found in the feed, then raise a ValueError. If ``include_arrows``, then use the Folium plugin PolyLineTextPath to draw arrows on each trip polyline indicating its direction of travel; this fails to work in some browsers, such as Brave 0.68.132. """ # Initialize map my_map = fl.Map(tiles="cartodbpositron") # Create colors n = len(trip_ids) colors = [color_palette[i % len(color_palette)] for i in range(n)] # Collect bounding boxes to set map zoom later bboxes = [] # Create a feature group for each route and add it to the map for i, trip_id in enumerate(trip_ids): collection = trips_to_geojson(feed, [trip_id], include_stops=include_stops) group = fl.FeatureGroup(name=f"Trip {trip_id}") color = colors[i] for f in collection["features"]: prop = f["properties"] # Add stop if present if f["geometry"]["type"] == "Point": lon, lat = f["geometry"]["coordinates"] fl.CircleMarker( location=[lat, lon], radius=8, fill=True, color=color, weight=1, popup=fl.Popup(hp.make_html(prop)), ).add_to(group) # Add trip else: path = fl.PolyLine( [[x[1], x[0]] for x in f["geometry"]["coordinates"]], color=color, popup=hp.make_html(prop), ) path.add_to(group) bboxes.append(sg.box(*sg.shape(f["geometry"]).bounds)) if include_arrows: # Direction arrows, assuming, as GTFS does, that # trip direction equals LineString direction fp.PolyLineTextPath( path, " \u27A4 ", repeat=True, offset=5.5, attributes={ "fill": color, "font-size": "18" }, ).add_to(group) group.add_to(my_map) fl.LayerControl().add_to(my_map) # Fit map to bounds bounds = so.unary_union(bboxes).bounds # Folium wants a different ordering bounds = [(bounds[1], bounds[0]), (bounds[3], bounds[2])] my_map.fit_bounds(bounds) return my_map
def tamam(self): self.nereden = self.comboBox.currentText() index1 = self.airport_name.index(self.nereden) self.nereye = self.comboBox_2.currentText() index2 = self.airport_name.index(self.nereye) if self.nereden == self.nereye: msg = QtWidgets.QMessageBox() msg.setText( "Aynı havalimanını seçemezsiniz\nProgram kendini imha edicek") msg.setWindowTitle("Uyarı") msg.setIcon(QtWidgets.QMessageBox.Information) msg.exec_() self.m = folium.Map(location=[38, 31], control_scale=True, zoom_start=6) self.m.add_child(folium.LatLngPopup()) # Tüm koordinatlar folium.raster_layers.TileLayer( # Farklı tür harita desenleri tiles='http://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}', attr='google', name='google maps', max_zoom=20, subdomains=['mt0', 'mt1', 'mt2', 'mt3'], overlay=False, control=True, ).add_to(self.m) folium.raster_layers.TileLayer( tiles='http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}', attr='google', name='google street view', max_zoom=20, subdomains=['mt0', 'mt1', 'mt2', 'mt3'], overlay=False, control=True, ).add_to(self.m) folium.LayerControl().add_to(self.m) self.m.add_child(MeasureControl()) # Mesafe ve Alan ölçer start = int(self.data[index1][0]) end = int(self.data[index2][0]) self.path_distance = (great_circle(start, end)) list_for_sketch = main(self.fname[0]) for i in range(len(list_for_sketch)): if [start, end] == list_for_sketch[i][0]: path = list_for_sketch[i][1] self.coor = list() for j in path: for i in range(len(self.data)): if j == int(self.data[i][0]): a = float(self.data[i][6]) b = float(self.data[i][7]) self.coor.append([a, b]) self.create_map() plane_line = folium.PolyLine(self.coor, weight=1, color='black').add_to(self.m) attr = {'font-weight': 'bold', 'font-size': '24'} plugins.PolyLineTextPath(plane_line, '\u2708 ', repeat=True, offset=8, attributes=attr).add_to(self.m) print("coor:", self.coor) print("list:", list) self.label_3.setText("Yönlendiriliyorsunuz...") self.m.save('shortest_route_map.html') os.startfile('shortest_route_map.html')