File size: 8,940 Bytes
ac64203
8d1de2d
ac64203
 
95d668a
ac64203
 
 
 
 
 
436fac5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcdd232
436fac5
 
fcdd232
436fac5
 
 
 
 
fcdd232
 
436fac5
 
ac64203
436fac5
 
 
 
ac64203
436fac5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac64203
 
436fac5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d1de2d
436fac5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac64203
436fac5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5bc736c
436fac5
 
 
 
 
 
 
 
 
 
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
import pandas as pd
import plotly.express as px
import streamlit as st
from lat_lon_parser import parse, to_str_deg_min_sec
from st_aggrid import AgGrid


class DataFrames:
    Dframe = pd.DataFrame()


def _validate_decimal_coordinate(value: float, axis: str) -> float:
    if axis == "lat" and not (-90 <= value <= 90):
        raise ValueError("Latitude must be between -90 and 90.")
    if axis == "lon" and not (-180 <= value <= 180):
        raise ValueError("Longitude must be between -180 and 180.")
    return value


def _decimal_to_dms_with_direction(value: float, axis: str) -> str:
    _validate_decimal_coordinate(value, axis)
    direction = "N" if value >= 0 else "S"
    if axis == "lon":
        direction = "E" if value >= 0 else "W"
    dms = to_str_deg_min_sec(abs(value))
    return f"{dms}{direction}"


def _dms_to_decimal(value: str, axis: str) -> float:
    normalized = value.strip().upper()
    if axis == "lon":
        normalized = normalized.replace("O", "W")
    result = parse(normalized)
    return _validate_decimal_coordinate(result, axis)


def _show_map(df: pd.DataFrame, lat_col: str, lon_col: str, title: str = "Map Visualization"):
    st.subheader(title)
    try:
        map_df = df.copy()
        map_df[lat_col] = pd.to_numeric(map_df[lat_col], errors="coerce")
        map_df[lon_col] = pd.to_numeric(map_df[lon_col], errors="coerce")
        map_df = map_df.dropna(subset=[lat_col, lon_col])

        if map_df.empty:
            st.warning("No valid coordinates available for map display.")
            return

        hover_cols = [col for col in map_df.columns if col not in [lat_col, lon_col]]
        if hover_cols:
            map_df["hover_text"] = map_df[hover_cols].astype(str).agg("<br>".join, axis=1)
        else:
            map_df["hover_text"] = "Point"

        fig = px.scatter_map(
            map_df,
            lat=lat_col,
            lon=lon_col,
            hover_name="hover_text",
            zoom=5,
            height=500,
        )
        fig.update_layout(
            mapbox_style="open-street-map",
            margin={"r": 0, "t": 0, "l": 0, "b": 0},
        )
        fig.update_traces(marker=dict(size=12, color="#FF4B4B"))
        st.plotly_chart(fig, use_container_width=True)
    except Exception as map_error:
        st.warning(f"Could not display map. Error: {map_error}")


def _render_import_mode():
    st.write("Convert coordinates from an Excel file.")

    decimal_to_degrees_sample_file_path = "samples/Decimal_to_DMS.xlsx"
    degrees_to_decimal_sample_file_path = "samples/DMS_to_Decimal.xlsx"

    col1, col2, _ = st.columns(3)

    with col1:
        st.download_button(
            label="Download Decimal_to_DMS Sample File",
            data=open(decimal_to_degrees_sample_file_path, "rb").read(),
            file_name="Decimal_to_DMS.xlsx",
            mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        )
    with col2:
        st.download_button(
            label="Download DMS_to_Decimal Sample File",
            data=open(degrees_to_decimal_sample_file_path, "rb").read(),
            file_name="DMS_to_Decimal.xlsx",
            mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        )

    uploaded_file = st.file_uploader("Choose a file", type=["xlsx"], key="gps_file")
    if uploaded_file is None:
        st.info("Please choose a file containing the latitude and longitude columns.")
        return

    DataFrames.Dframe = pd.read_excel(uploaded_file, keep_default_na=False)
    columns = DataFrames.Dframe.columns.tolist()

    latitude_col = st.selectbox("Choose Latitude Column", options=columns)
    longitude_col = st.selectbox("Choose Longitude Column", options=columns)
    conversion_choice = st.selectbox(
        "Choose Conversion Type",
        options=["DMS to Decimal", "Decimal to DMS"],
    )

    if not st.button("CONVERT", type="primary", key="import_convert"):
        return

    try:
        df = DataFrames.Dframe.copy()
        df["converted_latitude"] = df[latitude_col]
        df["converted_longitude"] = df[longitude_col]

        if conversion_choice == "DMS to Decimal":
            df["converted_latitude"] = df["converted_latitude"].apply(
                lambda x: _dms_to_decimal(str(x), "lat")
            )
            df["converted_longitude"] = df["converted_longitude"].apply(
                lambda x: _dms_to_decimal(str(x), "lon")
            )
            map_lat_col = "converted_latitude"
            map_lon_col = "converted_longitude"
        else:
            df["converted_latitude"] = pd.to_numeric(df["converted_latitude"], errors="coerce")
            df["converted_longitude"] = pd.to_numeric(df["converted_longitude"], errors="coerce")
            if df["converted_latitude"].isna().any() or df["converted_longitude"].isna().any():
                raise ValueError("Decimal columns contain invalid numeric values.")

            df["converted_latitude"] = df["converted_latitude"].apply(
                lambda x: _decimal_to_dms_with_direction(float(x), "lat")
            )
            df["converted_longitude"] = df["converted_longitude"].apply(
                lambda x: _decimal_to_dms_with_direction(float(x), "lon")
            )
            map_lat_col = latitude_col
            map_lon_col = longitude_col

        DataFrames.Dframe = df
        st.success("Coordinates converted successfully.")

        AgGrid(
            DataFrames.Dframe,
            fit_columns_on_grid_load=True,
            theme="streamlit",
            enable_enterprise_modules=True,
            filter=True,
        )

        _show_map(DataFrames.Dframe, map_lat_col, map_lon_col)

    except Exception as error:
        st.error(
            "An error occurred. Ensure your selected columns contain valid coordinate values. "
            f"Details: {error}"
        )


def _render_manual_mode():
    st.write("Convert a single coordinate pair without importing a file.")
    mode = st.radio(
        "Choose manual conversion type",
        options=["Decimal -> DMS", "DMS -> Decimal"],
        horizontal=True,
    )

    if mode == "Decimal -> DMS":
        col1, col2 = st.columns(2)
        with col1:
            latitude = st.number_input(
                "Latitude (decimal)",
                min_value=-90.0,
                max_value=90.0,
                value=0.0,
                step=0.000001,
                format="%.8f",
            )
        with col2:
            longitude = st.number_input(
                "Longitude (decimal)",
                min_value=-180.0,
                max_value=180.0,
                value=0.0,
                step=0.000001,
                format="%.8f",
            )

        if st.button("Convert Decimal -> DMS", type="primary", key="manual_decimal_to_dms"):
            try:
                lat_dms = _decimal_to_dms_with_direction(float(latitude), "lat")
                lon_dms = _decimal_to_dms_with_direction(float(longitude), "lon")
                st.success("Conversion successful.")
                st.write(f"Latitude (DMS): `{lat_dms}`")
                st.write(f"Longitude (DMS): `{lon_dms}`")

                map_df = pd.DataFrame([{"latitude": latitude, "longitude": longitude}])
                _show_map(map_df, "latitude", "longitude", title="Map Visualization (manual input)")
            except Exception as error:
                st.error(f"Invalid input. Details: {error}")

    else:
        col1, col2 = st.columns(2)
        with col1:
            latitude_dms = st.text_input(
                "Latitude (DMS)",
                placeholder="Example: 13 15 6.20N",
            )
        with col2:
            longitude_dms = st.text_input(
                "Longitude (DMS)",
                placeholder="Example: 2 10 5.00W",
            )

        if st.button("Convert DMS -> Decimal", type="primary", key="manual_dms_to_decimal"):
            try:
                latitude = _dms_to_decimal(latitude_dms, "lat")
                longitude = _dms_to_decimal(longitude_dms, "lon")
                st.success("Conversion successful.")
                st.write(f"Latitude (decimal): `{latitude:.10f}`")
                st.write(f"Longitude (decimal): `{longitude:.10f}`")

                map_df = pd.DataFrame([{"latitude": latitude, "longitude": longitude}])
                _show_map(map_df, "latitude", "longitude", title="Map Visualization (manual input)")
            except Exception as error:
                st.error(f"Invalid DMS value. Details: {error}")


st.title(":material/explore: GPS Coordinate Converter")
st.write(
    "Convert coordinates between Decimal and Degree-Minute-Second (DMS). "
    "You can convert from an Excel file or by entering values manually."
)

tab_import, tab_manual = st.tabs(["Import Excel", "Manual Input"])
with tab_import:
    _render_import_mode()
with tab_manual:
    _render_manual_mode()