def show_map(): latitude = 48.445 longitude = 21.687 np.random.seed(3141592) initial_data = ( np.random.normal(size=(300, 2)) * np.array([[0.003, 0.003]]) + np.array([[latitude, longitude]])) move_data = np.random.normal(size=(300, 2)) * 0.00001 data = [(initial_data + move_data * i).tolist() for i in range(100)] weight = 1 # default value for time_entry in data: for row in time_entry: row.append(weight) mapa = folium.Map([48.726, 21.249], tiles='OpenStreetMap', zoom_start=14) hm = HeatMapWithTime(data, auto_play=True, max_opacity=0.8, radius=5) hm.add_to(mapa) ref = db.reference('vines') result = ref.get() for res in result: folium.Marker(location=[ float(result[res]['latitude']), float(result[res]['longitude']) ], popup=result[res]['class'], icon=folium.Icon(color='green')).add_to(mapa) mapa.save('mapa.html') return send_file('mapa.html')
def heatmap(gdf, geometry_column='geometry', with_time=False, time_column='Year', name=None, show=False, basemap=None, **kwargs): """ Create a heatmap or a heatmap with time from a geodataframe of points. :param gdf: Geodataframe with points as the geometry type. :param geometry_column: The geometry column of the gdf. Defaults to 'geometry' :param start_color: The start color, defaults to 'white' :param end_color: The end color, defaults to the MI blue :param with_time: If true, plot a heat map with time, not just a heat map. :param time_column: The column used to specify the years of the data, defaults to 'Year' :param str name: Defaults to None. If not None, will generate a FeatureGroup with this name and return that instead of the GeoJson object. :param bool show: Defaults to False. The show parameter for the FeatureGroup that the GeoJson will be added to. :param folium.Map basemap: Defaults to None. If not none, will add the GeoJson or FeatureGroup to the supplied basemap. :param **kwargs: kwargs to be passed onto the 'heatmap' or 'heatmapwithtime' folium constructors. :return: HeatMap object or FeatureGroup """ if with_time: all_points = [] time_periods = sorted(gdf[time_column].unique().tolist()) for time_period in time_periods: points = gdf.loc[gdf[time_column] == time_period, geometry_column] points = [ utilities.simple.retrieve_coords(point) for point in points ] all_points.append(points) result = HeatMapWithTime(all_points, index=time_periods, **kwargs) else: points = [ utilities.simple.retrieve_coords(point) for point in gdf[geometry_column] ] result = HeatMap(points, **kwargs) if name is not None: feature_group = folium.FeatureGroup(name, show=show) result.add_to(feature_group) if basemap is not None: feature_group.add_to(basemap) return feature_group else: if basemap is not None: result.add_to(basemap) return result
time = row['date_start'] iframe = folium.IFrame(table('Deaths', name, deaths, time), width=width, height=height) popups[year].append(iframe) h = folium.FeatureGroup(name='Deaths') print(len(locations)) print(len(popups)) #for year in tqdm(conflict_df.date_start.unique()-1989): # # mc = MarkerCluster(locations=locations[year], popups=popups[year], overlay=True, control=True) # mc.add_to(m) #folium.LayerControl().add_to(m) h.add_child(FastMarkerCluster(locations)) #m.add_child(h) m.save(os.path.join('results', "output_map.html")) m = folium.Map(tiles='cartodbpositron', world_copy_jump=True, no_wrap=True) event_list = conflict_df[["latitude", "longitude", "best", "date_start"]] list_of_event = [[row.latitude, row.longitude, row.best] for row in event_list.itertuples()] date_list = [row.date_start for row in event_list.itertuples()] hm = HeatMapWithTime(data=list_of_event[:100], index=event_list.date_start[:100], max_opacity=0.3) hm.add_to(m) m.save(os.path.join('results', "output_map_heat.html"))
date_index = [] for day in data_df.day.sort_values().unique(): date_index.append(str(day)) df_day_list.append( data_df.loc[data_df.day == day, ['latitude', 'longitude', 'frac_corona']].groupby( ['latitude', 'longitude']).sum().reset_index().values.tolist()) from folium.plugins import HeatMapWithTime x = HeatMapWithTime(df_day_list, radius=5, index=date_index, auto_play=True, gradient={ 0.2: 'blue', 0.4: 'lime', 0.6: 'orange', 1: 'red' }, min_opacity=0.5, max_opacity=0.8, use_local_extrema=True) x.add_to(base_map) base_map.save('indonesia_over_time.html') #os.system("scp -i ~/.ssh/wb_indonesia_data_instance.pem indonesia_over_time.html [email protected]:/var/www/html/"); os.system('mv indonesia_over_time.html /var/www/html/')
def create_uk_accidents_viz(): ''' Load and pre-process the UK accidents data ''' # Load the accidents data df_accidents_path = os.path.normpath( os.path.join(script_dir_path, '..', 'data', 'Accidents1115.csv')) fields = [ 'Accident_Index', 'Latitude', 'Longitude', 'Date', 'Accident_Severity' ] df_accidents = pd.read_csv(df_accidents_path, index_col='Accident_Index', usecols=fields) # Format and sort by date df_accidents['Date'] = pd.to_datetime(df_accidents['Date'], format='%Y-%m-%d', errors='raise') df_accidents.sort_values('Date', inplace=True) # Drop the rows in which there's no lat lon data df_accidents = df_accidents[df_accidents['Latitude'].notna()] df_accidents.to_csv(df_accidents_path) # Leave only the 2015 accidents df_accidents = df_accidents[df_accidents['Date'].dt.year == 2015] # Get the heatmap index values heatmap_time_dates = df_accidents['Date'].dt.strftime( '%Y-%m-%d %A').unique().tolist() # Get the heatmap data heatmap_time_data = [] for date in heatmap_time_dates: df_accidents_daily = df_accidents.loc[df_accidents['Date'] == date] heatmap_time_data.append(df_accidents_daily[['Latitude', 'Longitude' ]].to_numpy().tolist()) ''' Initialize the map ''' map_accidents = folium.Map(location=[54, -2.4220], zoom_start=6, max_bounds=True, min_zoom=3, max_lat=60, max_lon=5, min_lat=49, min_lon=-12) ''' Create the map content and add it to the map object ''' # Create the HeatMapWithTime heatmap = HeatMapWithTime(heatmap_time_data, index=heatmap_time_dates, name='Traffic accidents in Great Britain (2015)', gradient={ .8: 'blue', .95: 'lime', .998: 'orange', 1: 'red' }, use_local_extrema=False, min_opacity=0, max_opacity=0.7, scale_radius=False) heatmap.add_to(map_accidents) # Create the legend template = utils.create_legend(caption='UK traffic accidents in 2015') macro = MacroElement() macro._template = Template(template) map_accidents.get_root().add_child(macro) ''' Save completed map viz to an appropriate folder ''' map_accidents.save( os.path.join(script_dir_path, '..', 'webapp', 'templates', 'UK_accidents_viz.html')) print('Successfully created the UK accidents viz!')