pjgerrits commited on
Commit
02ed674
1 Parent(s): d5ff9e4

updates control and sidebar

Browse files
Files changed (1) hide show
  1. app.py +90 -94
app.py CHANGED
@@ -1,14 +1,11 @@
1
  import streamlit as st
2
  import folium
3
  from streamlit_folium import st_folium
4
- from folium.plugins import Draw, Geocoder, MiniMap
5
  import psycopg2
6
- import pandas as pd
7
 
8
  st.set_page_config(layout="wide")
9
 
10
- # Database connection
11
- @st.cache_resource
12
  def connect_to_db():
13
  return psycopg2.connect(
14
  dbname="glprui_jloddr",
@@ -19,7 +16,6 @@ def connect_to_db():
19
  sslmode="prefer"
20
  )
21
 
22
- # Function to submit data
23
  def submit_data(age, gender, transport, multi_transport, time_of_day, day_of_week, description, points):
24
  conn = connect_to_db()
25
  cursor = conn.cursor()
@@ -36,14 +32,13 @@ def submit_data(age, gender, transport, multi_transport, time_of_day, day_of_wee
36
  record_id = cursor.fetchone()[0]
37
 
38
  for pointType, point in points.items():
39
- if point:
40
- cursor.execute(
41
- """
42
- INSERT INTO public.gettinglost_geom (ID, PointType, geom)
43
- VALUES (%s, %s, ST_SetSRID(ST_Point(%s, %s), 4326));
44
- """,
45
- (record_id, pointType, point[1], point[0])
46
- )
47
 
48
  conn.commit()
49
  st.success("Data recorded successfully!")
@@ -54,101 +49,102 @@ def submit_data(age, gender, transport, multi_transport, time_of_day, day_of_wee
54
  cursor.close()
55
  conn.close()
56
 
57
- # Initialize session state for points
58
- if 'points' not in st.session_state:
59
- st.session_state['points'] = {'start': None, 'lost': None, 'end': None}
60
- if 'step' not in st.session_state:
61
- st.session_state['step'] = 1
62
-
63
- # Sidebar for marker management
64
- st.sidebar.title("Step 1: Add Markers on the Map")
65
-
66
- # Selector for point type
67
- point_type = st.sidebar.radio("Select Point Type to Add", ["start", "lost", "end"])
68
-
69
- # Buttons to clear points
70
- if st.sidebar.button("Clear All Markers"):
71
- st.session_state['points'] = {'start': None, 'lost': None, 'end': None}
72
- st.rerun()
73
-
74
- if st.sidebar.button("Clear Selected Marker"):
75
- st.session_state['points'][point_type] = None
76
- st.rerun()
77
-
78
- # Create a placeholder for the map
79
- map_placeholder = st.empty()
80
-
81
- def create_map():
82
- # Initialize map
83
  m = folium.Map(location=[51.5074, -0.1278], zoom_start=10, control_scale=True)
84
-
85
- # Add existing points to the map
86
- for pointType, coords in st.session_state['points'].items():
87
  if coords:
88
  folium.Marker(
89
  location=coords,
90
- popup=pointType,
91
- icon=folium.Icon(color="red" if pointType == "start" else "blue" if pointType == "end" else "orange")
92
  ).add_to(m)
93
-
94
- # Add click functionality without creating popups
95
- draw = Draw(
96
- export=False,
97
- draw_options={
98
- "circle": False,
99
- "polyline": False,
100
- "polygon": False,
101
- "rectangle": False,
102
- "circlemarker": False,
103
- "marker": True,
104
- },
105
- edit_options={"edit": False}
106
- )
107
- draw.add_to(m)
108
- Geocoder(add_marker=True).add_to(m)
109
- MiniMap().add_to(m)
110
-
111
  return m
112
 
113
- # Display map
114
- with map_placeholder.container():
115
- output = st_folium(create_map(), width="100%", height=600, key="map")
116
-
117
- # Check for map click data
118
- if output and 'last_clicked' in output and output['last_clicked'] is not None:
119
- lat = output['last_clicked']['lat']
120
- lon = output['last_clicked']['lng']
121
- st.session_state['points'][point_type] = (lat, lon)
122
- st.rerun()
123
-
124
- # Display current points
125
- st.write("Current Points:", st.session_state['points'])
126
-
127
- # Step 2: Survey questions
128
- if st.session_state['step'] == 1:
129
- if st.sidebar.button("Done Adding Markers"):
130
- st.session_state['step'] = 2
131
- st.rerun()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
 
133
- if st.session_state['step'] == 2:
134
- st.sidebar.title("Step 2: Fill Out the Survey")
135
 
136
- age = st.sidebar.selectbox("Age", ["0-10", "11-20", "21-30", "31-40", "41-50", "51-60", "61-70", "71-80", "81-90", "91-100"])
137
- gender = st.sidebar.radio("Gender", ["M", "F", "O", "PNTS"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  transport = st.sidebar.radio("Mode of Transport", ["Walk", "Car", "Bike", "Train", "Other", "Multi"])
139
-
140
- multi_transport = []
141
- if transport == "Multi":
142
- multi_transport = st.sidebar.multiselect("If Multi, Select Modes Used", ["Walk", "Car", "Bike", "Train", "Other"])
143
-
144
  time_of_day = st.sidebar.selectbox("Time of Day", ["Morning", "Afternoon", "Evening", "Night"])
145
  day_of_week = st.sidebar.selectbox("Day of the Week", ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])
146
  description = st.sidebar.text_area("Why did you get lost?")
147
 
148
  if st.sidebar.button("Save"):
149
  submit_data(age, gender, transport, multi_transport, time_of_day, day_of_week, description, st.session_state['points'])
 
 
 
 
 
 
150
 
151
- st.sidebar.markdown("---")
152
- st.sidebar.markdown("For a more detailed survey, click the link or scan the QR code:")
153
- st.sidebar.markdown("[https://arcg.is/1GK5jP0](https://arcg.is/1GK5jP0)")
154
- st.sidebar.image("static/Getting Lost Survey.png", width=200)
 
1
  import streamlit as st
2
  import folium
3
  from streamlit_folium import st_folium
 
4
  import psycopg2
 
5
 
6
  st.set_page_config(layout="wide")
7
 
8
+ @st.cache(allow_output_mutation=True)
 
9
  def connect_to_db():
10
  return psycopg2.connect(
11
  dbname="glprui_jloddr",
 
16
  sslmode="prefer"
17
  )
18
 
 
19
  def submit_data(age, gender, transport, multi_transport, time_of_day, day_of_week, description, points):
20
  conn = connect_to_db()
21
  cursor = conn.cursor()
 
32
  record_id = cursor.fetchone()[0]
33
 
34
  for pointType, point in points.items():
35
+ cursor.execute(
36
+ """
37
+ INSERT INTO public.gettinglost_geom (ID, PointType, geom)
38
+ VALUES (%s, %s, ST_SetSRID(ST_Point(%s, %s), 4326));
39
+ """,
40
+ (record_id, pointType, point[0], point[1])
41
+ )
 
42
 
43
  conn.commit()
44
  st.success("Data recorded successfully!")
 
49
  cursor.close()
50
  conn.close()
51
 
52
+ def create_map(points):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  m = folium.Map(location=[51.5074, -0.1278], zoom_start=10, control_scale=True)
54
+ for point_type, coords in points.items():
 
 
55
  if coords:
56
  folium.Marker(
57
  location=coords,
58
+ popup=point_type,
59
+ icon=folium.Icon(color="red" if point_type == "start" else "blue" if point_type == "end" else "orange")
60
  ).add_to(m)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  return m
62
 
63
+ if 'points' not in st.session_state:
64
+ st.session_state['points'] = {'start': None, 'lost': None, 'end': None}
65
+ if 'survey' not in st.session_state:
66
+ st.session_state['survey'] = False
67
+
68
+ # Custom CSS for colored buttons
69
+ st.markdown(
70
+ """
71
+ <style>
72
+ .marker-button {
73
+ display: inline-block;
74
+ padding: 10px 20px;
75
+ margin: 5px;
76
+ border-radius: 5px;
77
+ cursor: pointer;
78
+ text-align: center;
79
+ color: white;
80
+ }
81
+ .start-button { background-color: red; }
82
+ .lost-button { background-color: orange; }
83
+ .end-button { background-color: blue; }
84
+ </style>
85
+ """,
86
+ unsafe_allow_html=True,
87
+ )
88
+
89
+ st.sidebar.title("Step 1 - Add Markers")
90
+
91
+ # Custom buttons for selecting point type
92
+ point_type = st.sidebar.radio(
93
+ "Select Point Type:",
94
+ ["start", "lost", "end"],
95
+ format_func=lambda x: x.capitalize()
96
+ )
97
+
98
+ if point_type == "start":
99
+ st.sidebar.markdown('<div class="marker-button start-button">Start</div>', unsafe_allow_html=True)
100
+ elif point_type == "lost":
101
+ st.sidebar.markdown('<div class="marker-button lost-button">Lost</div>', unsafe_allow_html=True)
102
+ elif point_type == "end":
103
+ st.sidebar.markdown('<div class="marker-button end-button">End</div>', unsafe_allow_html=True)
104
 
105
+ map_placeholder = st.empty()
 
106
 
107
+ with map_placeholder.container():
108
+ folium_map = create_map(st.session_state['points'])
109
+ map_output = st_folium(folium_map, width="100%", height=500)
110
+
111
+ new_coords = None
112
+ if map_output and 'last_clicked' in map_output and map_output['last_clicked'] is not None:
113
+ new_coords = (map_output['last_clicked']['lat'], map_output['last_clicked']['lng'])
114
+
115
+ if new_coords:
116
+ st.session_state['points'][point_type] = new_coords
117
+ map_placeholder.empty()
118
+ with map_placeholder.container():
119
+ folium_map = create_map(st.session_state['points'])
120
+ st_folium(folium_map, width="100%", height=500)
121
+
122
+ if all(st.session_state['points'].values()) and not st.session_state['survey']:
123
+ if st.sidebar.button("Proceed to Survey"):
124
+ st.session_state['survey'] = True
125
+ else:
126
+ st.sidebar.warning("Please add start, lost, and end points to proceed.")
127
+
128
+ if st.session_state['survey']:
129
+ st.sidebar.title("Step 2 - Survey Questions")
130
+ age = st.sidebar.selectbox("Age", list(range(10, 101, 10)))
131
+ gender = st.sidebar.radio("Gender", ["Male", "Female", "Other", "Prefer not to say"])
132
  transport = st.sidebar.radio("Mode of Transport", ["Walk", "Car", "Bike", "Train", "Other", "Multi"])
133
+ multi_transport = st.sidebar.multiselect("If Multi, select modes used", ["Walk", "Car", "Bike", "Train", "Other"]) if transport == "Multi" else []
 
 
 
 
134
  time_of_day = st.sidebar.selectbox("Time of Day", ["Morning", "Afternoon", "Evening", "Night"])
135
  day_of_week = st.sidebar.selectbox("Day of the Week", ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])
136
  description = st.sidebar.text_area("Why did you get lost?")
137
 
138
  if st.sidebar.button("Save"):
139
  submit_data(age, gender, transport, multi_transport, time_of_day, day_of_week, description, st.session_state['points'])
140
+ st.session_state['points'] = {'start': None, 'lost': None, 'end': None}
141
+ st.session_state['survey'] = False
142
+ st.experimental_rerun()
143
+
144
+ # st.sidebar.write("Current Points:")
145
+ # st.sidebar.json(st.session_state['points'])
146
 
147
+ st.sidebar.markdown("---")
148
+ st.sidebar.markdown("For a more detailed survey, click the link or scan the QR code:")
149
+ st.sidebar.markdown("[https://arcg.is/1GK5jP0](https://arcg.is/1GK5jP0)")
150
+ st.sidebar.image("static/Getting Lost Survey.png", width=200)