def map_multiple_outputs_points(directory: str, map_center=None, save_path=None): """ Creates a folium map of single or multiple outputs from the LP model. Circle markers communicate both location of station and forecast demand (diameter). Good for outputs from LP model that outputs points - not hexes. """ station_locations = open_station_locations() if not map_center: m_lat = station_locations[:1]['latitude'] m_long = station_locations[:1]['longitude'] else: m_lat = map_center[0] m_long = map_center[1] m = Map( location=[m_lat, m_long], tiles='cartodbpositron', zoom_start=9 ) colors = ['blue', 'crimson', 'violet', 'orange', 'yellow', 'black'] cnt = 0 for file in os.listdir(directory): open_path_1 = f'data/GIS/LP_outputs/{file}' print(file) name = file.rstrip('.csv') proposed_stations_1 = open_lp_proposed_stations(lp_proposed_stations_path=open_path_1) proposed_stations_1.set_index('id', inplace=True) proposed_stations_1 = join_dfs(station_locations, proposed_stations_1) feature_group = FeatureGroup(name=name) for i, row in proposed_stations_1.iterrows(): if row['demand'] == 0: pass else: c = CircleMarker( radius=row['demand'], location=[row["latitude"], row["longitude"]], tooltip=f"Station ID: {row.name} \n Demand: {row['demand']} kWh", color=colors[cnt], fill=True, fill_color=colors[cnt] ) c.add_to(feature_group) feature_group.add_to(m) cnt += 1 LayerControl('bottomright', collapsed=False).add_to(m) if save_path: m.save(save_path) return m
def create_map(df_collisions, df_stations, boroughs): geo_map = Map(location=[40.74527, -73.988573], tiles=None, zoom_start=12, control_scale=True) close_distance = 200 # meters # collisions TileLayer('Stamen Terrain', name='Collision Data').add_to(geo_map) for borough in boroughs: feature_group = FeatureGroup(name=borough.capitalize()) marker_cluster = MarkerCluster().add_to(feature_group) df_collisions[df_collisions['borough'] == borough].apply( lambda r: Marker( location=[r['latitude'], r['longitude']], tooltip=f"{r['cyclist_injured'] + r['cyclist_killed']} cyclists injured/killed", icon=Icon(color='darkblue', icon='exclamation-circle', prefix='fa')).add_to(marker_cluster), axis=1) feature_group.add_to(geo_map) # bike stations quartiles = df_stations['close_collisions'].quantile([0.25, 0.5, 0.75]).tolist() feature_group = FeatureGroup(name='Bike Stations') df_stations.apply(lambda r: CircleMarker( location=(r['latitude'], r['longitude']), radius=2, color=get_color(r['close_collisions'], quartiles), tooltip=f"Bike Station {int(r['id'])}: {int(r['close_collisions'])} collisions within {close_distance}m", fill=True).add_to(feature_group), axis=1) feature_group.add_to(geo_map) LayerControl(collapsed=False).add_to(geo_map) geo_map.save('templates/map.html')
def create_tcircle_marker(row, mm, mid, mad): return CircleMarker(location=[row.lat, row.lon], radius=3 * row.prefMag, popup=create_popup(row.date, row.depth, row.prefMag), color='black', fill=True, weight=2, fill_opacity=1.0, fill_color=get_tcolor(row.date, mid, mad)).add_to(mm)
def draw_score_markers(data, folium_map, congestions_toggle): cmap = plt.get_cmap('RdYlBu_r') # Sort by score to get higher score markers on top of the map data = sorted(data, key=lambda k: k['score'], reverse=congestions_toggle) norm = colors.Normalize(vmin=-1, vmax=1) placed_markers = set() try: for row in data: color = convert_to_hex(cmap(norm(row['score']))) tooltip = 'Location: {}<br />Attribute: {}<br />Time: {}<br />Score: {}'.format( row['location'].replace('{', '').replace('`', '').replace('}', ''), row['attribute_name'], row['time_point'], row['score']) # Only place a marker per location # TODO: change to max/min per location if row['location'] in placed_markers: continue if row['dataset'] == 'espiras': pmarker = CircleMarker(location=json.loads(row['location_coor']), radius=8, line_color=color, color=color, fill_color=color, tooltip=tooltip) pmarker.add_to(folium_map) else: if isinstance(row['location_coor'], dict): row['location_coor'] = str(row['location_coor']) geojson = GeoJson( row['location_coor'].replace("\'", "\""), style_function=lambda f, color=color: { 'fillColor': color, 'color': color, 'weight': 4, 'fillOpacity': 0.7 }, tooltip=tooltip ) geojson.add_to(folium_map) placed_markers.add(row['location']) except Exception as e: print(e)
def plotDot(point): '''Takes a series that contains a list of floats named latitude and longitude and this function creates a CircleMarker and adds it to your this_map''' CircleMarker(location=[point.latitude, point.longitude], fill_color=cmap(point[color_var]), fill=True, fill_opacity=0.4, radius=40, weight=0).add_to(this_map)
def add_value(self, values, multiplier=4): values = self._pandas_to_list(values) for record in values: value = record[2] location_info = record[0:2] color = "#ff0000" if value >= 0 else "#000000" # pos and neg have different colors CircleMarker(location=location_info, radius=multiplier * abs(value), alpha=0.5, fill=True, fill_color=color, color=color).add_to(self.canvass) return self
def add_volcanoes(map): map = map volcanoes = read_excel('volcanoes.xlsx').iloc[1:, [1, 2, 4, 5, 6]] latitudes, longitudes = volcanoes['Latitude'], volcanoes['Longitude'] name = volcanoes['Volcano Name'] country = volcanoes['Country'] elevation = volcanoes['Elev'] fg_volcanoes = FeatureGroup(name='Volcanoes', show=False) def color_by_elevation(elev): if type(elev) == str: return 'white' if elev <= -4000: return 'darkblue' if elev <= -2000: return 'cadetblue' if elev <= 0: return 'lightblue' if elev <= 2000: return 'orange' if elev <= 4000: return 'red' if elev <= 6000: return 'darkred' else: return 'black' for i in range(len(volcanoes)): i += 1 if isnan(elevation[i]): elevation[i] = 'Unknown' if name[i] == 'Unnamed': html = f'Volcano name:{name[i]}<br>Height: {elevation[i]} m<br> {country[i]}' else: html = f'Volcano name:<b4> <a href="https://www.google.com/search?q={name[i]} volcano" target="_blank">{name[i]}</a><br> \ Height: {elevation[i]} m<br> {country[i]}' iframe = IFrame(html=html, width=200, height=100) coords = (latitudes[i], longitudes[i]) fg_volcanoes.add_child( CircleMarker(location=coords, popup=Popup(iframe), color="gry", fill_color=color_by_elevation(elevation[i]), fill_opacity=0.9, radius=6)) i -= 1 map.add_child(fg_volcanoes)
def make_location_map(self): m = Map(location=self.updater.origin, zoom_start=10) Circle(location=self.updater.origin, fill_color='white', radius=self.updater.max_dist * 1609.34, weight=2, color="#000").add_to(m) CircleMarker(self.updater.origin, popup="Origin", radius=3, fill=True, color='red').add_to(m) for item in self.updater.in_range.values(): if item.location.coords: CircleMarker(item.location.coords, popup=item.location.name, radius=3, fill=True, color='blue').add_to(m) else: print(f"{item.location.name} -- {item.location.address}") m.save("H-E-B map.html") webbrowser.open('H-E-B map.html')
def get_volcanoes_feature_group() -> FeatureGroup: feature_group = FeatureGroup(name="Volcanoes") data = pandas.read_csv("./Volcanoes_USA.txt") latitudes = list(data['LAT']) longitudes = list(data['LON']) elevation = list(data['ELEV']) for lat, lon, elev in zip(latitudes, longitudes, elevation): feature_group.add_child( CircleMarker(location=(lat, lon), color='grey', weight=1, radius=6, popup=Popup(str(elev) + "m", parse_html=True), fill_color=get_elevation_color(elev))) return feature_group
def add_circles(self, points: Union[DataFrame, list], lat_col: str, lon_col: str, y_col: str, multiplier: float = 2, **kwargs) -> SpatialPlot: """ the difference between the add_circle and add_marker is that the former uses the size of the circle to visualize the value observed at that point :param points: either a dataframe or a list with location info and the values observed at the location :param lat_col: the column name (str) for latitude information :param lon_col: the column name (str) for longitude information :param y_col: the column name (str) for observed value at that location :param multiplier: size of the point. Increase this value to get large circles. """ if isinstance(points, DataFrame): if lat_col not in points or lon_col not in points or y_col not in points: raise KeyError( 'We need a column for latitude information and a column for longitude' ) df_points = points elif isinstance(points, list): logger.critical( 'we will assume the first position is latitude,' ' and the second is longitude, and the third position is y') df_points = DataFrame(points).iloc[:, 0:3] df_points.columns = [lat_col, lon_col, y_col] else: raise TypeError( 'only list and dataframe are supported in this method') df_points = df_points[[lat_col, lon_col, y_col]] self.update_locations(new_data=df_points, lat_col=lat_col, lon_col=lon_col) self.initialize_canvass() for idx, row in df_points.iterrows(): value = row[y_col] location = (row[lat_col], row[lon_col]) CircleMarker(location=location, radius=multiplier*abs(value), **kwargs) \ .add_to(self.canvass) return self
def _create_marker(cls, layer_value: str, coordinates: [float], layer_figure: ObjectFigure) -> CircleMarker: """ Create single Folium CircleMarker object. :param layer_value: (str) value of layers data_field to display on markers popup. :param coordinates: [float] coordinates on which the marker should be displayed :param layer_figure: (ObjectFigure) layer figure configuration object. :return: (Marker) marker instance adjusted for provided params. """ return CircleMarker(location=coordinates, radius=layer_figure.size * cls._scale, popup=layer_value, fill_color=layer_figure.colour, fill=True, color='grey', fill_opacity=layer_figure.opacity)
def compute_map(df): lat = list(df['lat']) lng = list(df['lng']) company_name = list(df['company_name']) map = Map(location=[15.2993, 74.1240], zoom_start=10) fgv = FeatureGroup() for lt, ln, name in zip(lat, lng, company_name): if not math.isnan(lt): fgv.add_child( CircleMarker(location=[lt, ln], radius=6, popup=name, fill_color="green", fill=True, color='grey', fill_opacity=0.7)) pass map.add_child(fgv) map.save(map_name)
def init_map(path, data): """ str, list -> folium map Creates a folium map .html file in the direction path. """ map = Map() data_group = FeatureGroup(name='Data Layer') geolocator = Nominatim(user_agent='shumakov') geocode = RateLimiter(geolocator.geocode, min_delay_seconds=0.01) for row in data: if not row[0] or not row[1]: continue pos = geolocator.geocode(row[1]) data_group.add_child( CircleMarker(location=[pos.latitude, pos.longitude], radius=7, popup=row[0], fill_color='red', color='white', fill_opacity=0.5)) map.add_child(data_group) map.save(path) return map
def add_layer(dataset, layername, mapname, color): """Plots predictions on a Leaflet map Creates a FeatureGroup to hold all of the points. FeatureGroup is added to the map as a layer. Args: dataset: a dataframe with the data to be plotted modelname: name of the model to be used as the layer name mapname: name of the map to be plotted on color: color used for the points in the layer Returns: a layer of points added to the map """ feature_group = FeatureGroup(name=layername) for point in dataset['geometry']: CircleMarker(location=[point.y, point.x], radius=4, color=color, fill_color=color).add_to(feature_group) feature_group.add_to(mapname)
def create_map(data, file_name="index.html"): map = Map( location=[data[col].mean() for col in ["latitude", "longitude"]], tiles="Stamen Toner", zoom_start=2, ) fg_nodes_locations = FeatureGroup(name="Locations") fg_nodes_counts = FeatureGroup(name="Counts") circles = [ { "radius": 5, "stroke": False, "fill": True, "fill_color": "crimson", "fill_opacity": opacity, "location": [latitude, longitude], "popup": Popup( html=f""" <style> tbody {{ text-align: center; }} table, tr, td {{ border-collapse: collapse; border: 1px solid black; }} </style> <h3>{ip}</h3> <table> <tbody> <tr> <td><strong>ISP</strong></td> <td>{org}</td> </tr> <tr> <td><strong>Completed requests</strong></td> <td>{completed_requests}</td> </tr> </tbody> </table> """, max_width=300, ), } for ip, latitude, longitude, org, completed_requests, opacity in [ named_tuple[2:] for named_tuple in data.itertuples(index=False) ] ] q1, q2, q3, q4 = nodes_counts_quantiles() def opacity(scaled_nodes_count): # print(scaled_nodes_count) if scaled_nodes_count < q1: return 0 elif q1 <= scaled_nodes_count < q2: return 0.1 elif q2 <= scaled_nodes_count < q3: return 0.25 elif q3 <= scaled_nodes_count < q4: return 0.5 else: return 0.75 def style_function(feature): fillOpacity = opacity(feature["properties"]["scaled_nodes_count"]) return {"fillColor": "blue", "weight": 0, "fillOpacity": fillOpacity} fg_nodes_counts.add_child( GeoJson( data=open("data/enriched_world.json", encoding="utf-8-sig").read(), style_function=style_function, ) ) for circle in circles: fg_nodes_locations.add_child(CircleMarker(**circle)) map.add_child(fg_nodes_counts) map.add_child(fg_nodes_locations) map.add_child(LayerControl()) map.save(file_name)
import json import urllib.request import urllib.request from folium import Map, CircleMarker, Marker map = Map() earthquake_API = urllib.request.urlopen("https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2014-01-02&endtime=2014-01-03") earthquake_API = earthquake_API.read().decode('utf-8') earthquake = json.loads(earthquake_API) for i in earthquake["features"]: map.add_child(CircleMarker(location=[-180, 180], popup="Test", color = "brown", fill_opacity = 0.3, radius=20, fill_color = "red")) break map.save('Map_1.html')
""".format feature_articulos.add_child( Marker([row['Latitud'], row['Longitud ']], popup=popup, tooltip=html_tooltip(row['Cita']), icon=Icon(color='red', icon='info-sign'))) feature_articulos.add_to(hospedero_map) for especie in df_resumen.Especie.unique(): temp_df = df_resumen[df_resumen['Especie'] == especie] # show_especie = True if especie == 'Carollia perspicillata' else False feature_group = FeatureGroup(especie, show=False) html_tooltip = """ <h4><i>{}</i></h4> <h5><b>Cantidad:</b> {}</h5> """.format temp_df.apply(lambda row: feature_group.add_child( CircleMarker([row['Latitud'], row['Longitud']], radius=5 * row['Cantidad'], tooltip=Tooltip(html_tooltip(especie, row['Cantidad'])), color=color_especie[especie], fill=True)), axis=1) feature_group.add_to(hospedero_map) folium.LayerControl().add_to(hospedero_map) hospedero_map.save('index.html')
alt.X("Year:Q", bin=alt.Bin( extent=[min(dane['Year'] - 1), max(dane['Year'] + 1)], step=1), axis=alt.Axis(format='.0f')), y='Value:Q', color=alt.Color( 'Balance', scale=alt.Scale( range=['black', 'red', "blue"]))).configure_axisX( labelAngle=90) vis1 = chart.to_json() plots.append(vis1) #ADD MARKER data = pd.read_csv('glacier_point.csv') for i in range(0, len(data)): for plot in plots: m.add_child( CircleMarker(location=[data['x'][i], data['y'][i]], popup=(folium.Popup(max_width=1000).add_child( folium.VegaLite(plots[i]))), fill_opacity=0.3, color="darkblue", fill_color=('white'), marker="o", markersize=16, markeredgewidth=1)) m.save('isbre.html')
data = pd.read_csv('Volcanoes_USA.txt') lat = data.get('LAT') lon = data.get('LON') elevation = data.get('ELEV') def color_change(elevation): if (elevation < 1000): return ('green') elif (1000 <= elevation < 3000): return ('orange') else: return ('red') map = Map(location=[37.296933, -121.9574983], zoom_start=5) marker_cluster = MarkerCluster().add_to(map) for lat, lon, elevation in zip(lat, lon, elevation): CircleMarker( location=[lat, lon], radius=9, popup='{} m'.format(str(elevation)), fill_color=color_change(elevation), color='gray', fill_opacity=0.9, ).add_to(marker_cluster) map.save('map1.html')
from folium import plugins, Map, Circle, CircleMarker, PolyLine from randomcoords import RandomCoords center_point = [ 34.062400, -117.894900 ] # Defining the center of our map as well as our RandomCoords objects # Making our first map, a 100km circle with 5000 points. map1 = Map(location=center_point, zoom_start=12) rc = RandomCoords(center=center_point, diameter=100, units='km') for point in rc.generate_coords(num_coords=5000): CircleMarker(location=point, radius=2, color='blue').add_to(map1) Circle(radius=50000, location=center_point, fill=False, color='red').add_to(map1) map1.save(r'C:\Users\User\Desktop\big_map_km.html') # Making our second map, a 10mi circle with 500 points. map2 = Map(location=center_point, zoom_start=12) rc2 = RandomCoords(center=center_point, diameter=10, units='mi') for point in rc2.generate_coords(num_coords=500): CircleMarker(location=point, radius=2, color='blue').add_to(map2) Circle(radius=8046, location=center_point, fill=False, color='red').add_to(map2) map2.save(r'C:\Users\User\Desktop\smaller_map_mi.html')
def virus_ncov2019(): tic = time.perf_counter() print('getting data') # confirmed_data, deaths_data, recovered_data, columns, dates_list, latest_data, countries_pops, new_data = get_data() confirmed_data, deaths_data, recovered_data, columns, dates_list, latest_data, countries_pops, new_data, US_data = get_data( ) print('data is fine') toc = time.perf_counter() print(f"Loaded data in {toc - tic:0.4f} seconds") # converting to 2d arrrays and getting totals confirmed_array = np.array(confirmed_data.iloc[:, 4:]).astype(int) confirmed_totals = np.sum(confirmed_array, axis=0) cur_confirmed = confirmed_totals[-1] recovered_array = np.array(recovered_data.iloc[:, 4:]).astype(int) recovered_totals = np.sum(recovered_array, axis=0) cur_recovered = recovered_totals[-1] deaths_array = np.array(deaths_data.iloc[:, 4:]).astype(int) deaths_totals = np.sum(deaths_array, axis=0) cur_deaths = deaths_totals[-1] confirmed_data.loc[confirmed_data.State == 0, 'State'] = '- ' recovered_data.loc[recovered_data.State == 0, 'State'] = '- ' deaths_data.loc[deaths_data.State == 0, 'State'] = '- ' start_point = ['40.7672726', '-73.9715264'] # new epicentre - NYC f_map = folium.Map(location=start_point, tiles='CartoDB dark_matter', zoom_start=8) sort_col = confirmed_data.columns[-1] confirmed_data = confirmed_data.sort_values(by=[sort_col], ascending=False) stats = confirmed_data.apply(lambda row: country_stat(row), axis=1) extended_stats = confirmed_data.apply( lambda row: country_stat_ext(countries_pops, row, deaths_data), axis=1) confirmed_diffs = confirmed_data[columns[0:4]].copy() for i in range(5, len(columns)): confirmed_diffs[columns[i]] = confirmed_data[ columns[i]] - confirmed_data[columns[i - 1]] # converting to 2d arrrays and getting totals confirmed_diffs_array = np.array(confirmed_diffs.iloc[:, 4:]).astype(int) confirmed_diffs_totals = np.sum(confirmed_diffs_array, axis=0) toc = time.perf_counter() print(f"Prepared data in {toc - tic:0.4f} seconds") #map all confirmed cases # row =4 tac = time.perf_counter() if new_data: for row in range(latest_data.shape[0]): cur_row = latest_data.iloc[row] if cur_row.Confirmed > 0: s_rad = radius_producer(cur_row.Confirmed) elif cur_row.Deaths > 0: s_rad = radius_producer(cur_row.Deaths) elif cur_row.Recovered > 0: s_rad = radius_producer(cur_row.Recovered) else: s_rad = 0 if s_rad > 0: html_popup = "<div class='code' style='background: rgba(212, 212, 255, 0.035)'><b>{}</b> <br>".format( cur_row.Full_name) + "Confirmed = {}".format( str(cur_row.Confirmed)) + " <br> Deaths = {}".format( str(cur_row.Deaths)) iframe = branca.element.IFrame(html=html_popup, width='250px', ratio="30%") popup = folium.Popup(iframe, max_width=500) CircleMarker([cur_row.Lat, cur_row.Long], radius=max(3, s_rad * 2), popup=popup, parse_html=True, fill_opacity=0.5, weight=0, fill=True, color=color_producer(1), fillColor=color_producer(1)).add_to(f_map) fast_map_html = f_map._repr_html_() f = open('data/map.html', 'w') f.write(fast_map_html) f.close() else: f = open('data/map.html', 'r') fast_map_html = f.read() f.close() toc = time.perf_counter() print(f"Processed main part in {toc - tic:0.4f} seconds") print(f"Made the map in {toc - tac:0.4f} seconds") ext_USA_states = US_data.apply(lambda row: US_state_ext(row), axis=1) return render_template( 'covid19.html', map_html=fast_map_html, last_update=dates_list[-1], x_Labels=dates_list, x_d_Labels=dates_list[1:], confirmed_totals=json.dumps(confirmed_totals.tolist()), recovered_totals=json.dumps(recovered_totals.tolist()), deaths_totals=json.dumps(deaths_totals.tolist()), confirmed_diffs_totals=json.dumps(confirmed_diffs_totals.tolist()), total_conf=f'{cur_confirmed:,}', total_recov=f'{cur_recovered:,}', total_deaths=f'{cur_deaths:,}', countries_list=json.dumps(stats.to_numpy().tolist()), ext_countries_list=json.dumps(extended_stats.to_numpy().tolist()), USA_data=json.dumps(ext_USA_states.to_numpy().tolist()))
map = folium.Map(location=start_point, tiles='CartoDB dark_matter', zoom_start=5) #map all confirmed cases for row in confirmed_list[1:]: s_rad = radius_producer(row[-1]) if s_rad > 0: if s_rad < 3: s_rad = s_rad * 2 CircleMarker([row[3], row[4]], radius=s_rad * 2, popup=row[0] + ' ' + row[1] + ' ' + '(Confirmed = ' + row[-1] + ')', fill_opacity=0.3, weight=2, fill=True, color=color_producer(1), fillColor=color_producer(1)).add_to(map) #map all deaths cases for row in deaths_list[1:]: s_rad = radius_producer(row[-1]) if s_rad > 0: CircleMarker([row[3], row[4]], radius=s_rad * 2, popup=row[0] + ' ' + row[1] + ' ' + '(Deaths = ' + row[-1] + ')', fill_opacity=0.3, weight=2,
def layer_gen(self, group, group_id, show): """ Generates a bubbles layer """ # Get the color of the bubble according to layer definitions color = 'blue' chart_options = self.options.get('chart_options', {}) for ind_index in range(len(chart_options.get('indicadores', []))): if chart_options.get('indicadores')[ind_index] == group_id: color = chart_options.get('colorArray')[ind_index] break # Adding circle radius to group, if it's not present in dataframe group if 'radius' not in group.columns: group['radius'] = self.assess_radius(group) if 'timeseries' not in chart_options: # Creating a layer for the group layer = FeatureGroup( name=ViewConfReader.get_layers_names(self.options.get('headers')).get(group_id), show=show ) # Check if popup data is present has_tooltip = 'tooltip' in group.columns # Generating circles for _row_index, row in group.iterrows(): tooltip_data = None if has_tooltip: tooltip_data = row['tooltip'] CircleMarker( location=[ row[chart_options.get('lat', 'latitude')], row[chart_options.get('long', 'longitude')] ], radius=row['radius'], popup=tooltip_data, color=color, fill=True, fill_color=color ).add_to(layer) # Adding layer to map return layer else: features = [] for _row_index, row in group.iterrows(): features.append({ 'type': 'Feature', 'geometry': { 'type': 'Point', 'coordinates': [ row[chart_options.get('long', 'longitude')], row[chart_options.get('lat', 'latitude')] ] }, 'properties': { 'time': pd.to_datetime( row[chart_options.get('timeseries', 'nu_competencia')], format='%Y' ).__str__(), 'style': {'color': color}, 'icon': 'circle', 'iconstyle': { 'fillColor': color, 'fillOpacity': 0.8, 'stroke': 'true', 'radius': row['radius'] } } }) return TimestampedGeoJson( features, period='P1Y', duration='P1Y', date_options='YYYY', transition_time=1000, auto_play=True )