*** Wartungsfenster jeden ersten Mittwoch vormittag im Monat ***

Skip to content
Snippets Groups Projects
Commit ad85b1a0 authored by Sharma, Sukrit's avatar Sharma, Sukrit
Browse files

comment map views

parent fd936a7e
Branches
No related tags found
No related merge requests found
......@@ -11,15 +11,24 @@ import plotly.graph_objects as go
import math
import branca
@group_required('map_group')
@group_required('map_group') # Restricts access to users in the 'map_group' group
def show_map(request):
"""
This view renders a map using Folium, displaying markers with custom popups
for location data and KPIs. The popups contain visualizations and consumption data.
"""
# Fetch data from LocationData model
dataquery = LocationData.objects.all()
# Convert data from the database into a pandas DataFrame
marker_data = read_frame(dataquery)
# Fetch KPI data using the custom kpi_map_marker function
kpi_data = kpi_map_marker()
# Replace NaN values in KPI data with 0
kpi_data = kpi_data.fillna(0)
# Define columns to check (all columns except 'zaehlpunkt')
......@@ -28,44 +37,32 @@ def show_map(request):
# Remove rows where all values in the specified columns are less than 0.1
kpi_data = kpi_data[~(kpi_data[cols_to_check] < 1).all(axis=1)]
# Merge the marker data with the KPI data based on 'Zaehlpunkt'
marker_data = pd.merge(marker_data, kpi_data, left_on='Zaehlpunkt', right_on='zaehlpunkt', how='right')
# Replace NaN values in the merged DataFrame with 0
marker_data = marker_data.fillna(0)
# Replace the substring in Zaehlpunkt with '...'
# Replace a specific substring in 'Zaehlpunkt' with '...'
marker_data['Zaehlpunkt'] = marker_data['Zaehlpunkt'].str.replace('000000000000001000', '...')
# Define the base URL for the basemap.at service
# Define the base URL for the basemap.at service to use as the map background
base_url = "http://maps.wien.gv.at/basemap/bmapgrau/normal/google3857/{z}/{y}/{x}.png"
# Define the available layers and their names
# layers = {
# "bmapgrau": "Gray",
# "geolandbasemap": "Basemap",
# "bmapoverlay": "Overlay",
# "bmaporthofoto30cm": "Orthophoto",
# "bmapgelaende": "Terrain",
# "bmapoberflaeche": "Surface"
# }
# Create a new map with Folium
m = folium.Map(width="100%", height="75%", location=[48.2082, 16.3738], zoom_start=12, control_scale=False, tiles = None)
# Create a new Folium map object, centered on Vienna with a specific zoom level
m = folium.Map(width="100%", height="75%", location=[48.2082, 16.3738], zoom_start=12, control_scale=False,
tiles=None)
# Add the basemap layer to the map
folium.TileLayer(tiles=base_url, attr="basemap.at", name="Gray").add_to(m)
# # Add the TileLayers for each layer
# for layer, name in layers.items():
# url = base_url.format(layer)
# folium.TileLayer(tiles=url, attr="basemap.at", name=name).add_to(m)
# Initialize MarkerCluster to group nearby markers
# Initialize a MarkerCluster to group nearby markers together on the map
marker_cluster = MarkerCluster().add_to(m)
# Dictionary to keep track of marker counts at each location
# Dictionary to track marker counts at each location (not used in this code)
marker_counts = {}
# Loop through DataFrame rows using iterrows()
# Loop through each row in the marker data DataFrame
for index, row in marker_data.iterrows():
Zaehlpunkt = row['Zaehlpunkt']
lat = row['Latitude']
......@@ -73,80 +70,63 @@ def show_map(request):
location = (lat, lon)
Address = row['Address']
Code = row['Code']
font_size = 2.5 * 30 // (len(Code)+1) # Adjust the range (8 to 12) as needed
###############
font_size = 2.5 * 30 // (len(Code) + 1) # Adjust font size based on Code length
# Prepare the data for consumption visualization
data = row.to_dict()
max_verbrauch = max([data['durchschnittliche_verbrauch_monatlich_max'],
data['aktueller_monatsverbrauch']])
# Calculate the maximum consumption for the current location
max_verbrauch = max([data['durchschnittliche_verbrauch_monatlich_max'], data['aktueller_monatsverbrauch']])
if max_verbrauch!=0 :
# Determine the logarithmic scale for consumption values
if max_verbrauch != 0:
exponent = math.floor(math.log10(abs(max_verbrauch)))
else:
exponent = 1
data['verbrauch_monatlich_max'] = (int(str(max_verbrauch)[0])+1)*10**exponent
# Update the consumption data
data['verbrauch_monatlich_max'] = (int(str(max_verbrauch)[0]) + 1) * 10 ** exponent
#data = {
# 'aktueller_monatsverbrauch': 500,
# 'durchschnittliche_verbrauch_monatlich_min': 200,
# 'durchschnittliche_verbrauch_monatlich_max': 800,
# 'verbrauch_monatlich_max': 1000
#}
# Create a DataFrame from the data
# Create a DataFrame for consumption data
df = pd.DataFrame(data, index=[0])
# Calculate values for stacked bars
# Prepare the data for stacked bar chart visualization
df['1.Durchschnittliche Min'] = df['durchschnittliche_verbrauch_monatlich_min']
df['2.Durchschnittliche Max'] = df['durchschnittliche_verbrauch_monatlich_max'] - df[
'1.Durchschnittliche Min']
df['2.Durchschnittliche Max'] = df['durchschnittliche_verbrauch_monatlich_max'] - df['1.Durchschnittliche Min']
df['3.Maximum'] = df['verbrauch_monatlich_max'] - df['2.Durchschnittliche Max']
# Melt the DataFrame to transform it into long format for plotting
df_melted = df.melt(value_vars=['1.Durchschnittliche Min', '2.Durchschnittliche Max','3.Maximum'], var_name='category', value_name='kWh')
# Transform the DataFrame into long format for use in Altair chart
df_melted = df.melt(value_vars=['1.Durchschnittliche Min', '2.Durchschnittliche Max', '3.Maximum'],
var_name='category', value_name='kWh')
#leg_order = ['segment_1', 'segment_2', 'segment_3']
# Define the base stacked bar chart with inverted stacking order
# Create the base stacked bar chart in Altair
base = alt.Chart(df_melted, title='Verbrauch dieser Monat').mark_bar().encode(
alt.X('kWh:Q', stack='zero'), # Invert stacking order based on color
color=alt.Color('category:N', #sort=leg_order,
scale=alt.Scale(
#domain=leg_order,
#domain=['Durchschnittliche Min', 'Durchschnittliche Max', 'Maximum'],
range=['green', 'orange', 'red']
),
legend=alt.Legend(title='',
orient='none',
legendY=55,
direction='horizontal'
))
alt.X('kWh:Q', stack='zero'),
color=alt.Color('category:N', scale=alt.Scale(range=['green', 'orange', 'red']),
legend=alt.Legend(title='', orient='none', legendY=55, direction='horizontal'))
)
# Overlay the stacked bar chart with the aktueller_monatsverbrauch
# Overlay the current month's consumption on top of the stacked bars
df_melt = df.melt(value_vars=['aktueller_monatsverbrauch'], var_name='category', value_name='kWh')
overlay = alt.Chart(df_melt).mark_bar(size=10).encode(
alt.X('kWh:Q', stack='zero'),
color=alt.value('blue'), # Set the color directly to blue
color=alt.value('blue'),
opacity=alt.value(1)
)
# Combine the base and overlay
# Combine the base chart with the overlay
chart = (base + overlay)
# Create an iframe with the Altair chart
iframe = folium.IFrame(chart.to_html(), width=300, height=300)
data = alt.Data(values=[{'x': 'A'}])
# Replace periods with commas in the relevant fields
# Prepare footer text with consumption values, formatted with commas
last_month = str(row.verbrauch_taeglich_last_month).replace('.', ',')
last_quarter = str(row.verbrauch_taeglich_last_quarter).replace('.', ',')
last_year = str(row.verbrauch_taeglich_last_year).replace('.', ',')
yesterday = str(row.verbrauch_taeglich_yesterday).replace('.', ',')
# Update the footer text with formatted values
# Construct the footer text to display in the popup
footer = [
f'Zaehlpunkt: {Zaehlpunkt}',
f'Address: {Address}',
......@@ -158,25 +138,18 @@ def show_map(request):
f'Gestern: {yesterday}'
]
text = (
alt.Chart(data)
.mark_text(text=footer, x=0, y='height', dx=0, dy=70, align='left', fontSize=18)
)
# Create Altair chart for footer text
text = alt.Chart(alt.Data(values=[{'x': 'A'}])).mark_text(text=footer, x=0, y='height', dx=0, dy=70,
align='left', fontSize=18)
# Combine the main chart with the footer text
chart = alt.layer(chart, text)
vega_lite = folium.VegaLite(
chart,
width="100%",
height="100%",
)
# Embed the chart into a VegaLite object to display in Folium popup
vega_lite = folium.VegaLite(chart, width="100%", height="100%")
popup = folium.Popup().add_child(vega_lite)
# Define custom marker UI (SVG icon)
# Define the custom marker UI (SVG with circle and text)
marker_ui = f"""
<div>
<svg width="100" height="100">
......@@ -187,11 +160,9 @@ def show_map(request):
</div>
"""
# Create marker with custom popup and UI, and add to marker cluster
folium.Marker(location=location, popup=popup, icon=folium.DivIcon(html=marker_ui), lazy=True).add_to(marker_cluster)
# Create a marker with the custom popup and UI, and add it to the marker cluster
folium.Marker(location=location, popup=popup, icon=folium.DivIcon(html=marker_ui), lazy=True).add_to(
marker_cluster)
# Render the map directly into the template and return it as a response
# Render the map to the template and return it as an HTML response
return render(request, 'map.html', {'map': m._repr_html_()})
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment