def plot_countie_map(df): df = sightings_per_state(df) df_sightings_per_countie = sightings_per_countie(df) # map init m = folium.Map(location=[48, -102], tiles='cartodbpositron', zoom_start=3) # counties layer_counties = folium.TopoJson(open(USA_countie_map), 'objects.counties', style_function=style_function) layer_counties.layer_name = 'counties' layer_counties.add_to(m) # states m.choropleth(geo_data=my_USA_map, data=df, columns=['State', 'Sightings'], key_on='feature.id', fill_color='YlGn', fill_opacity=0.2, line_opacity=0.2, legend_name='UFO sightings in the US', name='states') folium.LayerControl().add_to(m) return m
def layer_gen(self, state_geo): """ Generates a choropleth layer """ chart_options = self.options.get('chart_options', {}) # Creating the choropleth layer color_scale = ViewConfReader.get_color_scale( self.options, self.dataframe[chart_options.get('value_field', 'vl_indicador')].min(), self.dataframe[chart_options.get('value_field', 'vl_indicador')].max() ) color_function = self.get_feature_color chart = folium.TopoJson( state_geo, 'objects.data', name=ViewConfReader.get_chart_title(self.options), style_function=lambda feature: { 'fillColor': color_function(color_scale, feature, chart_options.get('value_field')), 'fillOpacity': 0.8, 'color': 'black', 'stroke': 'black', 'lineOpacity': 0.2, 'weight': 0.2, } ) # Adding tooltip to choropleth folium.features.GeoJsonTooltip( fields=[hdr.get('value') for hdr in self.options.get('headers')], aliases=[hdr.get('text') for hdr in self.options.get('headers')], localize=True, sticky=False, labels=True ).add_to(chart) return chart
def folium_map(df, x, y, location, countries_topodata, colormap, zoom=1): results_map_income = folium.Map(location, tiles='OpenStreetMap', zoom_start=zoom) #creating dictionary to easily find the UDC voting rate dictionary = df.set_index(x)[y] #clean_data.set_index('CantonID')['UDC'] #Our own choropleth folium.TopoJson( countries_topodata, # open('data/contries.topojson.json'), 'objects.countries1', style_function=lambda x: { 'fillColor': '#black' if (x['id'] not in dictionary.index.values) or (pd.isnull( dictionary[x['id']])) else colormap(dictionary[x['id']]), 'color': 'black', 'weight': 0.5, 'dashArray': '5, 5', 'fillOpacity': 0.9, }, tooltip=folium.GeoJsonTooltip( fields=['name'], aliases=[''], sticky=True, style="font-family: Arial; color: black;", opacity=0.8, direction='top')).add_to(results_map_income) results_map_income.add_child(colormap) #adding legend to map return results_map_income
def createmap(request): try: # Setup the database connection connection = mysql.connector.connect(host="localhost", database="geospatial_okan", user="******", password="******") if connection.is_connected(): global cursor cursor = connection.cursor(buffered=True) cursor.execute("select database();") m = folium.Map(locations=[-112.48849364, 33.3596368342], zoom_start=12, tiles='OpenStreetMap',control_scale=True) # Used to insert Counties into the map data = [json.loads(line) for line in open('/Users/nischalkashyap/Downloads/Fall 2020/Research Assistant GIS/database/djangoapp/geospatial/visualization/templates/visualization/us_geoson.json','r')] folium.TopoJson(data[0], 'objects.us_counties_20m', name='topojson').add_to(m) query = "Select * from county;" cursor.execute(query) rows = cursor.fetchall() query = "Select * from commodity;" cursor.execute(query) commodities = cursor.fetchall() for i in rows: query = "Select * from mesoscale where origin_county = '"+str(i[0])+"' or dest_county='"+str(i[0])+"';" cursor.execute(query) data = cursor.fetchall() commodity_values = [] for j in data: commodity_values.append(j[5]) query = "Select * from fm_lm_connections where origin_county_code = '" + str(i[0]) + "' or destination_county_code='" + str(i[0]) + "';" cursor.execute(query) data = cursor.fetchall() for j in data: commodity_values.append(j[5]) popup_source = '<strong>'+str(i[1])+'</strong>' popup_source+='<form action="visualization" method="post">' popup_source+='<select name="commodity" id="commodity" class="form-control input-lg">' for comm in commodities: if comm[0] in commodity_values: popup_source+='<option value="'+str(comm[0])+'">'+str(comm[0])+'</option>' popup_source+='</select><br/>' popup_source += '<select name="county" id="county" class="form-control input-lg"><option value="'+str(i[0])+'">'+str(i[1])+'</option></select><br/>' popup_source += '<select name="transfer" id="transfer" class="form-control input-lg"><option value="FM">FM</option><option value="FM-MESOSCALE">FM-MS</option><option value="MESOSCALE INFLOWS">MSINF</option><option value="MESOSCALE OUTFLOWS">MSOUT</option><option value="MESOSCALE-LM">MS-LM</option><option value="LM">LM</option></select><br /><input type="submit" class="btn btn-primary my-2" value="Visualize"></form>' tooltip = "Click for More Info" popup = folium.Popup(popup_source,max_width=10000000) folium.Marker([i[3], i[4]], popup=popup, tooltip=tooltip, icon=folium.Icon(icon='cloud', color='blue')).add_to(m) m.save('visualization/templates/visualization/map.html') return render(request, "visualization/map.html") except Error as e: return render(request, "visualization/databaseerror.html") finally: if (connection.is_connected()): cursor.close() connection.close()
def ice_edge_layer(): """ -> layer Returns a layer marked with Antarctica ice cover """ ice = folium.FeatureGroup(name="Ice Edge") return ice.add_child( folium.TopoJson(open('antarctic_ice_shelf_topo.json'), 'objects.antarctic_ice_shelf'))
def get_density_map_(): ''' return map with density layer normalized reports per country not normalized reports per country markers of airbases ''' # geo data geo_data_folder = './geo_data/' us_state_map = geo_data_folder + r'us-states.json' us_countie_map = geo_data_folder + r'us-topo.json' # map init m = folium.Map( location=[48, -102], tiles='cartodbpositron', zoom_start=3 ) # densities layer layer_densities = folium.TopoJson( open(us_countie_map), 'objects.counties', style_function=style_function_density ).add_to(m) layer_densities.layer_name = 'population density' # colorscale m.add_child(colorscale) # airbases cluster map df_airbases = process_airbases() cluster_markers = folium.plugins.MarkerCluster().add_to(m) tooltip = 'click!' for index, row in df_airbases.iterrows(): folium.Marker( location=[row.latitude, row.longitude], popup='<i>'+row.base_name+'</i>', icon=folium.Icon(icon='plane', color="white", icon_color='black') ).add_to(cluster_markers) cluster_markers.layer_name = "airbase markers" folium.LayerControl().add_to(m) return m
def make_folium_map(json_map_path, object_path, color_func, vmin, vmax, colors_table, location, zoom_start, legend_name): cantons_path = os.path.join('', json_map_path) topo_json_data = json.load(open(cantons_path)) m = folium.Map(location=location, zoom_start=zoom_start) folium.TopoJson(topo_json_data, object_path=object_path, style_function=lambda feature: { 'fillColor': color_func(feature['id']), 'fillOpacity': 0.9, 'line_opacity': 0.3, 'weight': 0.4, }).add_to(m) linear = folium.colormap.StepColormap(colors=colors_table, vmin=vmin, vmax=vmax, caption=legend_name).add_to(m) return m
def global_visualization(topo_json_data, countries, df, factor, layer_name): """ The function is used to create popup map. Parameters: topo_json_data: The geometric data. countries: Lists of countries with data. df: The dataframe containing information to plot. factor: The column of dataframe to plot. layer_name: Returned layer name Return: The layer to be added over map. """ popup = folium.FeatureGroup(name=layer_name, overlay=True, show=True) colormap1 = createcm(df, factor) for data in topo_json_data['objects']['countries1']['geometries']: country_topo = copy.deepcopy(topo_json_data) country_topo['objects']['countries1']['geometries'] = [data] country_name = country_topo['objects']['countries1']['geometries'][0][ 'properties']['name'] country_layer = folium.TopoJson(country_topo,object_path = 'objects.countries1',control=False, show = False, style_function = lambda feature:{ 'fillColor': color_map(feature['properties']['name'],\ colormap1,countries,df,factor), 'color' : 'black', 'fillOpacity': 1, 'weight' : 1, 'dashArray' : '5, 5' }) if country_name not in countries: country_layer.add_child( folium.Tooltip(country_name + ': data not collected.')) else: country_layer.add_child( folium.Tooltip('The ' + factor + ' of ' + country_name + ' is :' + str(df.loc[country_name][factor]))) country_layer.add_to(popup) return popup
state = int(state_dict[feature["properties"]["name"]]) data = icu.at[state, "allbed_mean"] data = np.log(1e-1) if data <= 0. else np.log(data) except Exception as e: data = np.log(1e-1) return { 'fillOpacity': 0.5, 'weight': 0, 'fillColor': '#black' if data is None else colorscale(data) } m = folium.Map(location=[38, -95], tiles='cartodbpositron', zoom_start=4) folium.TopoJson(state_json, 'objects.states', style_function=style_function).add_to(m) m.save("result/icu-%s.html" % date) DRIVER = 'chromedriver' driver = webdriver.Chrome(DRIVER) "result/icu-%s.html" % "2020-03-19" driver.get( 'file:///C:/Users/Alexander/Desktop/COVID-19-Analysis/result/icu-%s.html' % date) screenshot = driver.save_screenshot('result/icu-%s.png' % date) driver.quit() foo = Image.open('result/icu-%s.png' % date) foo = foo.resize((600, 400), Image.ANTIALIAS) foo.save('result/icu-%s.png' % date, quality=20, optimize=True)
def county_plot(): folium.TopoJson(open(county_overlay), object_path='objects.GBR_adm2', style_function=style_function).add_to(m)
import json import folium import requests url = 'https://raw.githubusercontent.com/python-visualization/folium/master/examples/data' antarctic_ice_edge = f'{url}/antarctic_ice_edge.json' antarctic_ice_shelf_topo = f'{url}/antarctic_ice_shelf_topo.json' m = folium.Map( location=[80.6016, 120], tiles='Mapbox Bright', zoom_start=2 # Limited levels of zoom for free Mapbox tiles. ) folium.GeoJson( antarctic_ice_edge, name='geojson' ).add_to(m) folium.TopoJson( json.loads(requests.get(antarctic_ice_shelf_topo).text), 'objects.antarctic_ice_shelf', name='topojson' ).add_to(m) folium.LayerControl().add_to(m) m.save("test2.html")
buoy_map.save('/tmp/folium_xx_NOAA_buoys.html') ############################################################################### antarctic_ice_edge = '/gdata/folium/data/antarctic_ice_edge.json' antarctic_ice_shelf_topo = '/gdata/folium/data/antarctic_ice_shelf_topo.json' m = folium.Map( location=[-59.1759, -11.6016], tiles='Mapbox Bright', zoom_start=2 ) folium.GeoJson( antarctic_ice_edge, name='geojson' ).add_to(m) folium.TopoJson( open(antarctic_ice_shelf_topo), 'objects.antarctic_ice_shelf', name='topojson' ).add_to(m) folium.LayerControl().add_to(m) m.save('/tmp/folium_xx_ice_map.html') ############################################################################### import folium import pandas as pd state_geo = '/gdata/folium/data/us-states.json' state_unemployment = '/gdata/folium/data/US_Unemployment_Oct2012.csv' state_data = pd.read_csv(state_unemployment) m = folium.Map(location=[48, -102], zoom_start=3) m.choropleth(geo_data=state_geo, name='choropleth', data=state_data, columns=['State', 'Unemployment'], key_on='feature.id', fill_color='YlGn', fill_opacity=0.7, line_opacity=0.2, legend_name='Unemployment Rate (%)')
import branca import folium import pandas as pd import requests colorscale = branca.colormap.linear.PuRd_09.scale(0, 100000) url = 'https://raw.githubusercontent.com/python-visualization/folium/master/examples/data' county_data = f'{url}/us_county_data.csv' county_geo = f'{url}/us_counties_20m_topo.json' df = pd.read_csv(county_data, na_values=[' ']) employed_series = df.set_index( 'FIPS_Code')['Median_Household_Income_2011'].dropna() def style_function(feature): employed = employed_series.get(int(feature['id'][-5:]), None) return { 'fillOpacity': 0.5, 'weight': 0, 'fillColor': '#black' if employed is None else colorscale(employed) } m = folium.Map(location=[48, -102], tiles='cartodbpositron', zoom_start=3) folium.TopoJson(json.loads(requests.get(county_geo).text), 'objects.us_counties_20m', style_function=style_function).add_to(m) '''显示m''' m
def draw_map(): try: os.remove("./templates/heatmap.html") except FileNotFoundError: pass global show_spread_zones, counties, epicenters map_data = pd.read_csv("data.csv", sep=',') url = 'https://raw.githubusercontent.com/python-visualization/folium/master/examples/data' county_geo = f'{url}/us_counties_20m_topo.json' colorscale = branca.colormap.LinearColormap(["white", "red"], vmin=0, vmax=0.1) employed_series = map_data.set_index('id')['indexlol'] def style_function(feature): employed = employed_series.get(int(feature['id'][-5:]), None) return { 'fillOpacity': 0.5, 'weight': 0, 'fillColor': '#black' if employed is None else colorscale(employed) } m = folium.Map(location=[38, -102], tiles='cartodbpositron', zoom_start=4.5) folium.TopoJson(json.loads(requests.get(county_geo).text), 'objects.us_counties_20m', style_function=style_function).add_to(m) if show_spread_zones: hmap_lat = [] hmap_long = [] hmap_indexes = [] for x in map_data.indexlol.values.tolist(): if x > 1.5: x_index = map_data.indexlol.values.tolist().index(x) hmap_lat.append(list(map_data.latitude.values)[x_index]) hmap_long.append(list(map_data.longitude.values)[x_index]) hmap_indexes.append(x) hmap_lat = tuple(hmap_lat) hmap_long = tuple(hmap_long) hmap_indexes = tuple(hmap_indexes) hmap = HeatMap(list(zip(hmap_lat, hmap_long, hmap_indexes)), min_opacity=0.5, radius=40, blur=17, max_zoom=1) m.add_child(hmap) points_to_render = epicenters + counties print(points_to_render) for item in points_to_render: for key, value in information.items(): if key == item: folium.Marker( location=[value['latitude'], value['longitude']], popup=folium.Popup( f"<h3>{key.split('_')[1]}, {key.split('_')[0]}</h3>" f"<br>Cases: {str(value['cases_current']).split('.')[0]}" f"<br>Increase of cases per day: {str(value['cases_diff']).split('.')[0]}" f"<br><br>Population: {str(value['population']).split('.')[0]}" f"<br>Population density: {str(value['population_density']).split('.')[0]}", max_width=300), icon=folium.Icon(color='blue'), ).add_to(m) print(m.to_json()) m.save('./templates/heatmap.html') return open("./templates/heatmap.html").read()
geo_json_data = json.load(open(europe_geo_path)) colorscale = branca.colormap.linear.YlOrRd.scale(data_total['2016'].min(), data_total['2016'].max()) def style_function(feature): d = data_total.loc[data_total['country'] == feature['id']]['2016'] return { 'fillOpacity': 0.8, 'weight': 1, 'fillColor': '#black' if d.size == 0 else colorscale(d.tolist()[0]) } centre_map = folium.Map(location=[-59.1759, -11.6016], tiles='Mapbox Bright', zoom_start=2) topojson_file = os.path.join('topojson', 'europe.topojson.json') with open(topojson_file) as file: folium.TopoJson(file, 'objects.europe', name='topojson', style_function=style_function).add_to(centre_map) #folium.LayerControl().add_to(centre_map) centre_map.add_child(colorscale) centre_map
res = res[res["Date"] == 0] colorscale = branca.colormap.linear.RdBu_09.scale(np.log(0.01), np.log(500)) def style_function(feature): try: #print("Hello") county = str(int(feature['id'][-5:])) #print(county) data = np.log(res.loc[county, "Resid"]) print(res.loc[county, "Resid"], data) except Exception as e: data = np.log(0.011) #print(data) #print("!!!!!") return { 'fillOpacity': 0.5, 'weight': 0, 'fillColor': '#black' if data is None else colorscale(data) } m = folium.Map(location=[38, -95], tiles='cartodbpositron', zoom_start=4) folium.TopoJson(uscountygeo, 'objects.us_counties_20m', style_function=style_function).add_to(m) m.save("result/result1.html")
county_geo = os.path.join('', 'countyGeo.json') df = pd.read_csv(county_data, na_values=[' ']) colorscale = branca.colormap.linear.YlOrRd_09.scale(0, 1) interested_data = df.set_index('County') def style_function(feature): key = feature['properties']['NAME'] data_y = interested_data.loc[key, 'Yes'] data_n = interested_data.loc[key, 'No'] data_b = interested_data.loc[key, 'Blanks'] data = float(data_y) / float(data_y + data_n) return { 'fillOpacity': 0.5, 'weight': 0, 'fillColor': '#black' if data is None else colorscale(data) } m = folium.Map(location=[42.407211, -71.382439], tiles='cartodbpositron', zoom_start=8) folium.TopoJson(open(county_geo), 'objects.cb_2015_massachusetts_county_20m', style_function=style_function).add_to(m) m.save('./templates/question.html')
#Add a TopoJson layer to the map for 2016 presidential election colorscale_election = branca.colormap.linear.RdBu.scale(0,1) election_series = election.set_index("combined_fips")["per_dem"] def style_function_election(feature): election_res = election_series.get(feature["id"][-5:], None) return { 'fillOpacity': 1, 'weight': 0.3, 'color': 'black', 'fillColor': 'white' if election_res is None else colorscale_election(election_res) } folium.TopoJson( open(county_geo), "objects.us_counties_20m", name="2016 presidential election", style_function=style_function_election ).add_to(m) #Add a GeoJson layer to the map for current US senate members senate_series = senate_parties.set_index("state_code")["party"] def senate_color_function(party): if party == -4: #2 gop return 'red' elif party == 0: #1 gop 1 dem return '#712ccc' elif party == 4: #2 dem return 'blue' else: #ind and gop/dem return '#d6b915'
def add_swiss_topo(m, style_function=None): folium.TopoJson(open(swiss_topo), 'objects.cantons', name="my name", style_function=style_function).add_to(m)
# Stamen Terrain, Stamen Toner, Mapbox Bright, and Mapbox Control Roo - Map Options map1 = folium.Map(location=[51.509865, -0.118092], tiles='Stamen Terrain', zoom_start=11.5) # When adding Json data, insert into Properties --> "scalerank": 5, "featurecla": "Name of Boundary" with open("outer_london.geojson", 'rb') as f: read = json.load(f) folium.GeoJson(data=read, name='Outer London Outline').add_to(map1) map1.save('colored.html') map2 = folium.Map(location=[51.509865, -0.118092], tiles='Stamen Toner', zoom_start=11.5) folium.TopoJson( data=open(r'BoroughJSON\Barking and Dagenham\topo_E09000002.json'), name='Barking and Dagenham', object_path='objects.E09000002', tooltip='Barking and Dagenham').add_to(map2) folium.TopoJson(data=open(r'BoroughJSON\Barnet\topo_E09000003.json'), name='Barnet', object_path='objects.E09000003', tooltip='Barnet').add_to(map2) folium.TopoJson(data=open(r'BoroughJSON\Bexley\topo_E09000004.json'), name='Bexley', object_path='objects.E09000004', tooltip='Bexley').add_to(map2) folium.TopoJson(data=open(r'BoroughJSON\Brent\topo_E09000005.json'), name='Brent', object_path='objects.E09000005', tooltip='Brent').add_to(map2) folium.TopoJson(data=open(r'BoroughJSON\Bromley\topo_E09000006.json'),
def plot(values_meso,last_mile_edges,first_mile_edges): #Create an instance of the map using Folium m = folium.Map(locations=[-112.48849364, 33.3596368342], zoom_start=12, tiles='OpenStreetMap', control_scale=True) #Used to insert Counties into the map data = [json.loads(line) for line in open('/Users/nischalkashyap/Downloads/Fall 2020/Research Assistant GIS/database/djangoapp/geospatial/visualization/templates/visualization/us_geoson.json', 'r')] folium.TopoJson(data[0], 'objects.us_counties_20m', name='topojson').add_to(m) #Based on user selection, project the necessary data onto the map #For First Mile to First Mile if USER_SELECTION == 'FM': #Used to keep track of all the nodes inserted onto the map marked_tracker = [] for i in first_mile_edges: val = i.split('*') fewsion_dollar_value = float(val[6]) edge = [[float(val[0]), float(val[1])], [float(val[3]), float(val[4])]] popup_source = '<strong>' + val[2] + '</strong>' popup_destination = '<strong>' + val[5] + '</strong>' tooltip = "Click for More Info" #Create markers on the map based on the nodes in the edge entity if val[0] + val[1] not in marked_tracker: folium.Marker([float(val[0]), float(val[1])], popup=popup_source, tooltip=tooltip, icon=folium.Icon(icon='cloud', color='red')).add_to(m) marked_tracker.append(val[0] + val[1]) if val[3] + val[4] not in marked_tracker: folium.Marker([float(val[3]), float(val[4])], popup=popup_destination, tooltip=tooltip, icon=folium.Icon(icon='cloud', color='red')).add_to(m) marked_tracker.append(val[3] + val[4]) #Make the edges size based on the fewsion dollar value of that particular edge if fewsion_dollar_value < 1: folium.PolyLine(edge, weight=1.0, color="green").add_to(m) elif fewsion_dollar_value >= 1 and fewsion_dollar_value < 2: folium.PolyLine(edge, weight=2.0, color="blue").add_to(m) else: folium.PolyLine(edge, weight=3.0, color="black").add_to(m) # For First Mile to Mesoscale elif USER_SELECTION == "FM-MESOSCALE": marked_tracker = [] for i in first_mile_edges: val = i.split('*') fewsion_dollar_value = float(val[6]) edge = [[float(val[0]), float(val[1])], [float(val[3]), float(val[4])]] popup_source = '<strong>' + val[2] + '</strong>' popup_destination = '<strong>' + val[5] + '</strong>' tooltip = "Click for More Info" if val[0] + val[1] not in marked_tracker: folium.Marker([float(val[0]), float(val[1])], popup=popup_source, tooltip=tooltip, icon=folium.Icon(icon='cloud', color='red')).add_to(m) marked_tracker.append(val[0] + val[1]) if val[3] + val[4] not in marked_tracker: folium.Marker([float(val[3]), float(val[4])], popup=popup_destination, tooltip=tooltip, icon=folium.Icon(icon='cloud', color='red')).add_to(m) marked_tracker.append(val[3] + val[4]) if fewsion_dollar_value < 1: folium.PolyLine(edge, weight=1.0, color="blue").add_to(m) elif fewsion_dollar_value >= 1 and fewsion_dollar_value < 2: folium.PolyLine(edge, weight=2.0, color="blue").add_to(m) else: folium.PolyLine(edge, weight=3.0, color="blue").add_to(m) transfer_data = values_meso[2] all_connections = {} #Logic to identify if any two entries are present which has same source node and destination node #If yes, we tend to aggregate the fewsion_dollar_value for i in transfer_data: if (i[0], i[1]) not in all_connections: all_connections[(i[0], i[1])] = float(i[2]) else: all_connections[(i[0], i[1])] += float(i[2]) #All Connections is a dictionary used to store the aggregated fewsion dollar values of two counties if present in the mesoscale data marked_tracker = [] for i in all_connections: source_county = i[0] destination_county = i[1] #find Coordinates for the source county query = "select latitude,longitude,county_name from county where county_id = '" + str(source_county) + "';" cursor.execute(query) row = cursor.fetchone() #find Coordinates for the destination county query = "select latitude,longitude,county_name from county where county_id = '" + str(destination_county) + "';" cursor.execute(query) row_dest = cursor.fetchone() #Store the fewsion dollar value of the respective edge fewsion_dollar_value = all_connections[i] edge = [[row[0], row[1]], [row_dest[0], row_dest[1]]] popup_source = '<strong>' + row[2] + '</strong>' popup_destination = '<strong>' + row_dest[2] + '</strong>' tooltip = "Click for More Info" # Create markers on the map based on the nodes in the edge entity if source_county not in marked_tracker: folium.Marker([row[0], row[1]], popup=popup_source, tooltip=tooltip, icon=folium.Icon (icon='cloud', color='green')).add_to(m) marked_tracker.append(source_county) folium.Marker([row_dest[0], row_dest[1]], popup=popup_destination, tooltip=tooltip, icon=folium.Icon (icon='cloud', color='green')).add_to(m) marked_tracker.append(destination_county) # plugins.AntPath(edge).add_to(m) -> This code is for displaying flow # Make the edges size based on the fewsion dollar value of that particular edge if fewsion_dollar_value < 1: folium.PolyLine(edge, weight=1.0, color="black").add_to(m) elif fewsion_dollar_value >= 1 and fewsion_dollar_value < 2: folium.PolyLine(edge, weight=2.0, color="black").add_to(m) else: folium.PolyLine(edge, weight=3.0, color="black").add_to(m) # For Mesoscale to Mesoscale elif USER_SELECTION == "MESOSCALE INFLOWS" or USER_SELECTION=='MESOSCALE OUTFLOWS': transfer_data = values_meso[2] all_connections = {} for i in transfer_data: if (i[0],i[1]) not in all_connections: all_connections[(i[0],i[1])] = float(i[2]) else: all_connections[(i[0], i[1])] += float(i[2]) marked_tracker = [] for i in all_connections: if i[0] == COUNTY_CODE or i[1]==COUNTY_CODE: source_county = i[0] destination_county = i[1] query = "select latitude,longitude,county_name from county where county_id = '"+str(source_county)+"';" cursor.execute(query) row = cursor.fetchone() query = "select latitude,longitude,county_name from county where county_id = '" + str(destination_county) + "';" cursor.execute(query) row_dest = cursor.fetchone() fewsion_dollar_value = all_connections[i] edge = [[row[0],row[1]],[row_dest[0],row_dest[1]]] popup_source = '<a href = "http://127.0.0.1:8000/" target="_blank">Google</a>' #popup_source = '<strong>'+row[2]+'</strong>' popup_destination = '<strong>'+row_dest[2]+'</strong>' tooltip = "Click for More Info" if source_county not in marked_tracker: folium.Marker([row[0],row[1]],popup=popup_source,tooltip = tooltip,icon=folium.Icon (icon='cloud',color='red')).add_to(m) marked_tracker.append(source_county) folium.Marker([row_dest[0], row_dest[1]], popup=popup_destination,tooltip=tooltip,icon=folium.Icon (icon='cloud',color='green')).add_to(m) marked_tracker.append(destination_county) plugins.AntPath(edge).add_to(m) '''if fewsion_dollar_value<1: folium.PolyLine(edge, weight=1.0, color="green").add_to(m) elif fewsion_dollar_value>=1 and fewsion_dollar_value<2: folium.PolyLine(edge, weight=2.0, color="blue").add_to(m) else: folium.PolyLine(edge, weight=3.0, color="black").add_to(m)''' # For Mesocale to Last Mile elif USER_SELECTION == "MESOSCALE-LM": marked_tracker = [] for i in last_mile_edges: val = i.split('*') fewsion_dollar_value = float(val[6]) edge = [[float(val[0]), float(val[1])], [float(val[3]), float(val[4])]] popup_source = '<strong>' + val[2] + '</strong>' popup_destination = '<strong>' + val[5] + '</strong>' tooltip = "Click for More Info" if val[0] + val[1] not in marked_tracker: folium.Marker([float(val[0]), float(val[1])], popup=popup_source, tooltip=tooltip, icon=folium.Icon(icon='cloud', color='red')).add_to(m) marked_tracker.append(val[0] + val[1]) if val[3] + val[4] not in marked_tracker: folium.Marker([float(val[3]), float(val[4])], popup=popup_destination, tooltip=tooltip, icon=folium.Icon(icon='cloud', color='red')).add_to(m) marked_tracker.append(val[3] + val[4]) if fewsion_dollar_value < 1: folium.PolyLine(edge, weight=1.0, color="green").add_to(m) elif fewsion_dollar_value >= 1 and fewsion_dollar_value < 2: folium.PolyLine(edge, weight=2.0, color="blue").add_to(m) else: folium.PolyLine(edge, weight=3.0, color="black").add_to(m) transfer_data = values_meso[2] all_connections = {} for i in transfer_data: if (i[0], i[1]) not in all_connections: all_connections[(i[0], i[1])] = float(i[2]) else: all_connections[(i[0], i[1])] += float(i[2]) marked_tracker = [] for i in all_connections: source_county = i[0] destination_county = i[1] query = "select latitude,longitude,county_name from county where county_id = '" + str(source_county) + "';" cursor.execute(query) row = cursor.fetchone() query = "select latitude,longitude,county_name from county where county_id = '" + str( destination_county) + "';" cursor.execute(query) row_dest = cursor.fetchone() fewsion_dollar_value = all_connections[i] edge = [[row[0], row[1]], [row_dest[0], row_dest[1]]] popup_source = '<strong>' + row[2] + '</strong>' popup_destination = '<strong>' + row_dest[2] + '</strong>' tooltip = "Click for More Info" if source_county not in marked_tracker: folium.Marker([row[0], row[1]], popup=popup_source, tooltip=tooltip, icon=folium.Icon (icon='cloud', color='red')).add_to(m) marked_tracker.append(source_county) folium.Marker([row_dest[0], row_dest[1]], popup=popup_destination, tooltip=tooltip, icon=folium.Icon (icon='cloud', color='green')).add_to(m) marked_tracker.append(destination_county) plugins.AntPath(edge).add_to(m) '''if fewsion_dollar_value < 1: folium.PolyLine(edge, weight=1.0, color="green").add_to(m) elif fewsion_dollar_value >= 1 and fewsion_dollar_value < 2: folium.PolyLine(edge, weight=2.0, color="blue").add_to(m) else: folium.PolyLine(edge, weight=3.0, color="black").add_to(m)''' # For Last Mile to Last Mile elif USER_SELECTION == 'LM': marked_tracker = [] for i in last_mile_edges: val = i.split('*') fewsion_dollar_value = float(val[6]) edge = [[float(val[0]), float(val[1])], [float(val[3]), float(val[4])]] popup_source = '<strong>' + val[2] + '</strong>' popup_destination = '<strong>' + val[5] + '</strong>' tooltip = "Click for More Info" if val[0] + val[1] not in marked_tracker: folium.Marker([float(val[0]), float(val[1])], popup=popup_source, tooltip=tooltip, icon=folium.Icon(icon='cloud', color='red')).add_to(m) marked_tracker.append(val[0] + val[1]) if val[3] + val[4] not in marked_tracker: folium.Marker([float(val[3]), float(val[4])], popup=popup_destination, tooltip=tooltip, icon=folium.Icon(icon='cloud', color='red')).add_to(m) marked_tracker.append(val[3] + val[4]) if fewsion_dollar_value < 1: folium.PolyLine(edge, weight=1.0, color="green").add_to(m) elif fewsion_dollar_value >= 1 and fewsion_dollar_value < 2: folium.PolyLine(edge, weight=2.0, color="blue").add_to(m) else: folium.PolyLine(edge, weight=3.0, color="black").add_to(m) #Save the Map m.save('visualization/templates/visualization/map.html')