File size: 3,938 Bytes
9914376
73b9278
 
 
 
 
 
 
 
 
a633cb2
41103fd
73b9278
 
0fff812
 
 
 
a72e1fa
0fff812
 
 
9914376
0fff812
 
 
 
73b9278
 
 
 
 
 
 
 
a633cb2
 
 
 
 
 
 
 
 
28194a7
 
a633cb2
28194a7
 
a633cb2
28194a7
 
 
 
 
 
 
73b9278
41103fd
73b9278
 
 
 
 
 
 
 
41103fd
 
 
73b9278
 
41103fd
 
 
 
 
 
73b9278
41103fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73b9278
41103fd
7480d60
 
 
 
41103fd
73b9278
 
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
import re
import json
import streamlit as st
import pandas as pd
import geopandas as gpd
import leafmap.foliumap as leafmap

# wide streamlit display
st.set_page_config(layout="wide")

file_url = st.query_params.get("file_url", None)
print(f"{file_url=}")

if file_url:
    if ("file_url" in st.session_state) and (st.session_state.file_url == file_url):
        st.toast("Using cached data")
        input_gdf = st.session_state.input_gdf
    else:
        st.session_state.file_url = file_url
        if file_url.startswith("https://drive.google.com/file/d/"):
            ID = file_url.replace("https://drive.google.com/file/d/", "").split("/")[0]
            file_url = f"https://drive.google.com/uc?id={ID}"

        input_gdf = gpd.read_file(file_url)
        input_gdf = input_gdf.to_crs(epsg=7761)  # Gujarat zone
        st.session_state.input_gdf = input_gdf
        st.toast("Data loaded and cached")

    def format_fn(x):
        return input_gdf.drop(columns=["geometry"]).loc[x].to_dict()

    input_geometry_idx = st.selectbox("Select the geometry", input_gdf.index, format_func=format_fn)
    geometry_gdf = input_gdf[input_gdf.index == input_geometry_idx]

    m = leafmap.Map()
    map_type = st.radio(
        "Select the map type",
        ["Esri Satellite Map", "Google Hybrid Map (displays place names)", "Google Satellite Map"],
    )
    if map_type == "Google Hybrid Map (displays place names)":
        st.write(
            "<h4><div style='text-align: center;'>Google Hybrid (displays place names)</div></h4>",
            unsafe_allow_html=True,
        )
        m.add_basemap("HYBRID")
    elif map_type == "Google Satellite Map":
        st.write("<h4><div style='text-align: center;'>Google Satellite</div></h4>", unsafe_allow_html=True)
        m.add_basemap("SATELLITE")
    elif map_type == "Esri Satellite Map":
        st.write("<h4><div style='text-align: center;'>Esri - 2024/10/10</div></h4>", unsafe_allow_html=True)
        m.add_wms_layer(
            "https://wayback.maptiles.arcgis.com/arcgis/rest/services/World_Imagery/WMTS/1.0.0/GoogleMapsCompatible/MapServer/tile/56450/{z}/{y}/{x}",
            layers="0",
        )
    else:
        st.error("Invalid map type")
        st.stop()
    m.add_gdf(
        geometry_gdf.to_crs(epsg=4326),
        layer_name="Geometry",
        zoom_to_layer=True,
        style_function=lambda x: {"color": "red", "fillOpacity": 0.0},
    )
    m.to_streamlit()

    # Metrics
    stats_df = pd.DataFrame()
    stats_df["Points"] = json.loads(geometry_gdf.to_crs(4326).to_json())["features"][0]["geometry"]["coordinates"]
    stats_df["Area (ha)"] = geometry_gdf.geometry.area.item() / 10000
    stats_df["Perimeter (m)"] = geometry_gdf.geometry.length.item()

    st.write("<h3><div style='text-align: center;'>Geometry Metrics</div></h3>", unsafe_allow_html=True)
    #     st.markdown(
    #         f"""| Metric | Value |
    # | --- | --- |
    # | Area (ha) | {stats_df['Area (ha)'].item():.2f} ha|
    # | Perimeter (m) | {stats_df['Perimeter (m)'].item():.2f} m |"""
    #     unsafe_allow_html=True)
    st.markdown(
        f"""
    <div style="display: flex; justify-content: center;">
        <table>
            <tr>
                <th>Metric</th>
                <th>Value</th>
            </tr>
            <tr>
                <td>Area (ha)</td>
                <td>{stats_df['Area (ha)'].item():.2f} ha</td>
            </tr>
            <tr>
                <td>Perimeter (m)</td>
                <td>{stats_df['Perimeter (m)'].item():.2f} m</td>
            </tr>
        </table>
    </div>
    """,
        unsafe_allow_html=True,
    )

    csv = stats_df.T.to_csv(index=True)
    st.download_button(
        "Download Geometry Metrics", csv, f"{file_url}_metrics.csv", "text/csv", use_container_width=True
    )

else:
    st.warning("Please provide a KML or GeoJSON URL as a query parameter, e.g., `?file_url=<your_file_url>`")