from collections import OrderedDict from flask import Flask, render_template, request import pandas as pd import geopandas as gpd import folium import json app = Flask(__name__) route_id_to_stops = pd.read_csv('data/route_id_to_stops.csv') stops_delay_count = pd.read_csv('data/stops_delay_count.csv') gdf_stops_delay_count = gpd.GeoDataFrame(stops_delay_count, geometry=gpd.points_from_xy(stops_delay_count['GTFS Longitude'], stops_delay_count['GTFS Latitude']), crs='EPSG:4326') gdf_subway = gpd.read_file('data/my_subway_lines.geojson') gdf_avg_inc = gpd.read_file('data/average_income_2021.geojson') total_delays_by_line = pd.read_csv('data/total_delay_time_by_lines.csv') total_delays_by_stop = pd.read_csv('data/total_delay_time_by_stops.csv') race = gpd.read_file('data/nyc-race.geojson') on_time = pd.read_csv("data/avg_terminal_on_time_performance.csv") def make_map(line, default_map): rt_id_to_stops = route_id_to_stops.set_index('route_id').T.to_dict('list') rt_id_to_stops = {k: v[0].split(', ') for k, v in rt_id_to_stops.items()} if line: zoom = 12 center = gdf_stops_delay_count[gdf_stops_delay_count['stop_id'].isin(rt_id_to_stops[line])][['GTFS Latitude', 'GTFS Longitude']].mean().tolist() else: center = [40.7128, -74.0060] zoom = 11 base_map = 'CartoDB Voyager' m = folium.Map(location=center, zoom_start=zoom, control_scale=True, prefer_canvas=True, tiles=base_map) income_choropleth = folium.Choropleth( geo_data=gdf_avg_inc, name='Income by Zip Code', data=gdf_avg_inc, columns=['ZipCode', 'B19013001'], key_on='feature.properties.ZipCode', fill_color='YlGnBu', fill_opacity=0.7, line_opacity=0.2, legend_name='Average Income', highlight=True, smooth_factor=0 ) income_tooltip = folium.GeoJsonTooltip( fields=['ZipCode', 'B19013001', 'Neighborhood', 'Borough'], aliases=['Zip Code:', 'Average Income:', 'Neighborhood:', 'Borough:'], sticky=True, opacity=0.9, direction='top', style="font-size: 12px; max-width: 300px;", ) income_choropleth.geojson.add_child(income_tooltip) race_choropleth = folium.Choropleth( geo_data=race, name='NYC Race Map', data=race, columns=['name', 'Total Population'], key_on='feature.properties.name', fill_color='YlOrBr', fill_opacity=0.7, line_opacity=0.2, legend_name='Total Population', highlight=True, smooth_factor=1.0 ) fields = ['Total Population', 'White alone', 'Black or African American Alone', 'American Indian and Alaska Native alone', 'Asian alone', 'Native Hawaiian and Other Pacific Islander Alone', 'Some other race alone', 'Two or more races','Hispanic or Latino (Total)'] aliases = [field + ':' for field in fields] race_tooltip = folium.GeoJsonTooltip( fields=['name', *fields], aliases=['Zip Code:', *aliases], sticky=True, opacity=0.9, direction='top', style="font-size: 12px; width: 100 vw;", ) if default_map == "income": m.add_child(income_choropleth) else: m.add_child(race_choropleth) race_choropleth.geojson.add_child(race_tooltip) if line: gdf_line = gdf_subway[gdf_subway['name'].str.contains(line)] else: gdf_line = gdf_subway folium.GeoJson(data=gdf_line, name='Subway Lines', style_function=lambda feature: { 'color': feature['properties']['RGB Hex'], 'weight': 7, 'opacity': 1, }, tooltip=folium.GeoJsonTooltip( fields=['Line/Branch'], aliases=['Subway Line:'], sticky=True, opacity=0.9, direction='top', style="font-size: 12px;", labels=True ) ).add_to(m) if line: stops = rt_id_to_stops[line] gdf_stops = gdf_stops_delay_count[gdf_stops_delay_count['stop_id'].isin(stops)] else: gdf_stops = gdf_stops_delay_count markers = folium.FeatureGroup(name='Stops') m.add_child(markers) marker_tooltip = 'Click for more info.' for _, row in gdf_stops.iterrows(): delay = row['Average Delay per Line'] if delay <= 0: color = 'blue' elif delay <= 60: color = 'green' else: color = 'red' # remove '[' and ']' from the list of branches branch = row['branch'].replace('[', '').replace(']', '') pop_up = f"""
Stop: {row['Stop Name']}
Borough: {row['Borough']}
Train Lines: {branch}
Average Delay per Line: {row['Average Delay per Line (mins)']}
Delays: {row['Delay Count']}
""" marker = folium.Marker( location=[row['GTFS Latitude'], row['GTFS Longitude']], popup=folium.Popup(pop_up, max_width=300), icon=folium.Icon(color=color, icon='info-sign'), tooltip=marker_tooltip ).add_to(m) marker.add_to(markers) # explain the colors of the subway lines legend_html = '''