File size: 3,279 Bytes
4433fdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import streamlit as st
import folium
from folium.plugins import Draw
from streamlit_folium import st_folium
import psycopg2
import os

# Set the page layout
st.set_page_config(layout="wide")

@st.cache_resource
def connect_to_db():
    return psycopg2.connect(**st.secrets["postgres"])

conn = connect_to_db()


# Function to connect to the database
# def connect_to_db():
#     try:
#         conn = psycopg2.connect(
#             dbname=st.write(st.secrets["DB_NAME"]),
#             user=st.write(st.secrets["DB_USER"]),
#             password=st.write(st.secrets["DB_PASS"]),
#             host=st.write(st.secrets["DB_HOST"]),
#             port=st.write(st.secrets["DB_PORT"]),
#             sslmode='prefer'
#         )
#         return conn
#     except Exception as e:
#         st.error(f"An error occurred while connecting to the database: {e}")
#         return None

# Function to fetch previously saved data points
def fetch_saved_data():
    # conn = connect_to_db()
    if conn:
        cursor = conn.cursor()
        cursor.execute('SELECT "X", "Y", description, gl_certainty FROM public.gettinglost_tracking')
        data = cursor.fetchall()
        cursor.close()
        # conn.close()
        return data
    return []

# Function to save data to the database
def save_data(lat, lon, description, rating):
    conn = connect_to_db()
    if conn:
        cursor = conn.cursor()
        cursor.execute('INSERT INTO public.gettinglost_tracking ("X", "Y", geom, description, gl_certainty) VALUES (%s, %s, ST_SetSRID(ST_MakePoint(%s, %s), 4326), %s, %s)', 
                       (lat, lon, lon, lat, description, rating))
        conn.commit()
        cursor.close()
        conn.close()
        st.sidebar.success("Data recorded successfully!")
    else:
        st.sidebar.error("Failed to save data.")


st.title('Getting Lost Mapping')

# Create the Folium map with Draw plugin for point markers
m = folium.Map(location=[51.505, -0.09], zoom_start=13, width=1500, height=600)
draw = Draw(draw_options={'polyline': False, "marker": True, 'rectangle': False, 'polygon': False, 'circle': False, 'circlemarker': False})
m.add_child(draw)

# Display previously saved data points on the map
for point in fetch_saved_data():
    lat, lon, desc, rating = point
    folium.Marker([lat, lon], popup=f"{desc} (Certainty: {rating})").add_to(m)

# Render the map
map_output = st_folium(m, width='100%', height=600)

try:
    # Extract coordinates from drawn point
    coords = map_output["all_drawings"][-1]["geometry"]["coordinates"]
    st.session_state.coord = coords
except:
    # Default coordinates if no point has been drawn yet
    coords = [0,0]

# Data Entry Form in the sidebar
st.sidebar.write("Click on the map to select a location, then fill out the form.")
description = st.sidebar.text_area("Description:")
rating = st.sidebar.selectbox('Certainty (1-5)', ['1', '2', '3', '4', '5'])

# Placeholder for clicked coordinates (this is a simplification and might not capture all map clicks in Streamlit)
clicked_lat = coords[1]  # Default value, should ideally be updated on map click
clicked_lon = coords[0]  # Default value, should ideally be updated on map click

if st.sidebar.button('Save'):
    save_data(clicked_lat, clicked_lon, description, rating)