import pandas as pd import streamlit as st from geopy.distance import geodesic from st_aggrid import AgGrid class DataFrames: Dframe = pd.DataFrame() st.title("Distance Calculator") st.write( """This app allows you to calculate the distance between two points in a dataframe. Please choose a file containing the latitude and longitude columns for the 2 points. """ ) distance_sample_file_path = "samples/distance.xlsx" # Create a download button st.download_button( label="Download Distance Calculator Sample File", data=open(distance_sample_file_path, "rb").read(), file_name="distance.xlsx", mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ) uploaded_file = st.file_uploader( "Upload Excel file", type=["xlsx"], accept_multiple_files=False, help="Upload the Excel file containing the latitude and longitude columns for the 2 points", ) if uploaded_file: DataFrames.Dframe = pd.read_excel(uploaded_file, keep_default_na=False) col1_list = DataFrames.Dframe.columns.tolist() latitude1_dd = st.selectbox( "Choose Latitude of point 1", col1_list, key="latitude1" ) longitude1_dd = st.selectbox( "Choose Longitude of point 1", col1_list, key="longitude1" ) latitude2_dd = st.selectbox( "Choose Latitude of point 2", col1_list, key="latitude2" ) longitude2_dd = st.selectbox( "Choose Longitude of point 2", col1_list, key="longitude2" ) def calculate_distance(row): coord1 = (row[latitude1_dd], row[longitude1_dd]) coord2 = (row[latitude2_dd], row[longitude2_dd]) return geodesic(coord1, coord2).meters if st.button("CALCULATE DISTANCE", type="primary"): try: df = DataFrames.Dframe.copy() df["distance_meters"] = df.apply(calculate_distance, axis=1) st.success("The distances are calculated successfully") DataFrames.Dframe = df @st.fragment def table_data(): if DataFrames.Dframe is not None: AgGrid( DataFrames.Dframe, fit_columns_on_grid_load=True, theme="streamlit", enable_enterprise_modules=True, filter=True, ) table_data() except Exception as e: st.error( f"An error occurred. Make sure the file contains the latitudes and longitudes columns. Error: {e}" ) else: st.info( "Please choose a file containing the latitude and longitude columns for the 2 points" )