The latitude and longitude coordinates of the starting point and end point I clicked on the map cannot be read on the folium map. At the same time, because the interactive functions of Streamlit and folium are limited, the callback function cannot be used

import streamlit as st
import folium
from streamlit_folium import folium_static
from geopy.distance import geodesic

# 初始化 session_state
if "start_coords" not in st.session_state:
    st.session_state.start_coords = None

if "end_coords" not in st.session_state:
    st.session_state.end_coords = None

if "clicked_coords" not in st.session_state:
    st.session_state.clicked_coords = []

st.title("点击地图选择起点和终点")

# 创建 Folium 地图
m = folium.Map(location=[40.712776, -74.005974], zoom_start=12)

# 添加地图点击事件的处理函数
def handle_click(event):
    lat = event.latlng[0]
    lon = event.latlng[1]
    st.session_state.clicked_coords.append((lat, lon))
    # 更新地图上的标记
    folium.Marker([lat, lon], popup=f"座標: ({lat}, {lon})").add_to(m)

# 添加地图点击事件
folium.Marker([0, 0], popup=None, icon=None, draggable=False).add_to(m)
m.add_child(folium.LatLngPopup())  # 添加坐标弹出窗口

# 将地图显示在 Streamlit 中
folium_static(m, width=800, height=600)

# 在 Streamlit 中添加按钮来选择起点和终点
if st.button("选择起点"):
    if len(st.session_state.clicked_coords) > 0:
        start_coords = st.session_state.clicked_coords[-1]  # 使用最后一个点击坐标作为起点
        st.session_state.start_coords = start_coords
        st.write("已选择起点:", start_coords)

if st.button("选择终点"):
    if len(st.session_state.clicked_coords) > 0:
        end_coords = st.session_state.clicked_coords[-1]  # 使用最后一个点击坐标作为终点
        st.session_state.end_coords = end_coords
        st.write("已选择终点:", end_coords)

# 显示已选择的起点和终点
if st.session_state.start_coords is not None:
    st.write("起点坐标:", st.session_state.start_coords)

if st.session_state.end_coords is not None:
    st.write("终点坐标:", st.session_state.end_coords)

# 计算距离并显示
if st.session_state.start_coords is not None and st.session_state.end_coords is not None:
    distance_km = geodesic(st.session_state.start_coords, st.session_state.end_coords).kilometers
    st.write("距离:", distance_km, "公里")