shukdevdatta123's picture
Update app.py
3270969 verified
import streamlit as st
import pandas as pd
import streamlit.components.v1 as components
# Load the Excel file
file_path = 'Dhaka Metro Rail Fare 2.XLSX' # Ensure the correct file path
df = pd.read_excel(file_path)
# Ensure necessary columns are present
required_columns = ['Origin', 'Destination', 'Fare (ΰ§³)']
if not all(col in df.columns for col in required_columns):
st.write("Please ensure the file contains 'Origin', 'Destination', and 'Fare' columns.")
else:
# Streamlit UI setup
st.title("Dhaka Metro Rail Fare Checker πŸš‡")
st.write("Below is the fare chart for Dhaka Metro Rail πŸ’Ά:")
# Instruction sidebar
st.sidebar.title("Instructions")
st.sidebar.write("""
**Welcome to the Dhaka Metro Rail Fare Checker! πŸš‡**
*How to use:*
1. **Select your Location station**:
- Choose the station you are currently at from the **"Select your Location"** dropdown menu.
2. **Select your destination(s)**:
- After selecting your origin station, you will see a list of available destination stations.
- Click on the **destination buttons** for the station(s) you wish to travel to.
- You can select multiple destinations to check fares for different routes at once.
3. **Fare Calculation**:
- The fare from your selected origin station to each of the selected destination(s) will be displayed below in the fare details section.
4. **Clear Destinations**:
- If you want to reset your selection of destinations, simply click the **"Clear All Destinations"** button to start fresh.
---
**Interactive Map**:
The interactive map of Dhaka Metro stations below allows you to visualize routes between your selected origin and destination(s). Use the map to explore stations, animate routes, and check locations on the map.
**Interactive Features**:
- **Source & Destination Dropdown**: Select your source and destination from the dropdown menus on the map.
- **Animate Route**: Click the **"Animate Route"** button to visually track the route between the selected source and destination stations.
- **Animate All Locations**: Click the **"Animate All Locations"** button to animate all stations and get a dynamic overview of the network.
- **Stop Animation**: If you want to stop the animation at any time, press the **"Stop Animation"** button.
Enjoy your journey on the Dhaka Metro! πŸš‰
If you encounter any issues or need assistance, feel free to [Contact Support on WhatsApp](https://wa.me/+8801719296601).
""")
# Define the default "Select Journey from" message
default_origin = "Select Journey from"
# Dropdown for selecting origin (with "Select Journey from" as a default placeholder)
origin = st.selectbox(
"Select your Location:",
[default_origin] + df['Origin'].unique().tolist(), # Add the "Select Journey from" option at the top
index=0 # Ensure the first option is selected by default
)
# Initialize session state for destination selection if not already set
if 'destination_select' not in st.session_state:
st.session_state.destination_select = []
# Display buttons for each destination in 3 columns
if origin != default_origin:
st.write(f"Select your destination(s) from {origin}:")
# Create 3 columns
cols = st.columns(3)
# Loop through all possible destinations and create a button for each in the columns
dest_buttons = df['Destination'].unique()
for i, dest in enumerate(dest_buttons):
col_idx = i % 3 # Determine column index based on button position
with cols[col_idx]:
if st.button(f"Select {dest}", key=f"btn_{dest}"):
if dest not in st.session_state.destination_select:
st.session_state.destination_select.append(dest)
else:
st.session_state.destination_select.remove(dest)
# Clear all selected destinations button
if st.button("Clear All Destinations"):
st.session_state.destination_select = []
# Display selected destinations and calculate fares
destinations = st.session_state.destination_select
if origin == default_origin:
st.write("Please select a valid origin station to proceed.")
elif origin and destinations:
# Filter the dataframe based on user selection
fare_data = df[(df['Origin'] == origin) & (df['Destination'].isin(destinations))]
# Display the fare data
# Display the fare data in a creative and aesthetic format
if not fare_data.empty:
for index, row in fare_data.iterrows():
origin_to_dest_fare = row['Fare (ΰ§³)']
destination = row['Destination']
# Creative output with icons, emojis, and styled text
fare_message = f"""
<div style="background-color: #f0f8ff; padding: 10px; margin-bottom: 12px; border-radius: 8px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);">
<h4 style="font-family: 'Arial', sans-serif; color: #003366;">
πŸš‡ <strong>{origin}</strong> to <strong>{destination}</strong> Fare
</h4>
<p style="font-family: 'Arial', sans-serif; font-size: 18px; color: #009688;">
πŸ’΅ Fare: <strong style="font-size: 20px; color: #e91e63;">{origin_to_dest_fare}ΰ§³</strong>
</p>
<p style="font-family: 'Arial', sans-serif; font-size: 14px; color: #555555;">
✨ Enjoy your journey on the Dhaka Metro! πŸš‰
</p>
</div>
"""
st.markdown(fare_message, unsafe_allow_html=True)
else:
st.write("No fare data available for the selected origin and destinations.")
else:
st.write("Please select both an origin and at least one destination.")
# Embedding the interactive map
st.write("### Interactive Map of Dhaka Metro Stations")
map_html = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interactive Map</title>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
<style>
/* Make map container responsive */
#map {
height: 70vh; /* Default height is 70% of the viewport height */
width: 100%; /* Full width */
}
/* Controls container: Flex layout for larger screens, column layout for smaller screens */
#controls {
padding: 10px;
display: flex;
justify-content: center;
align-items: center;
gap: 10px;
background-color: #D8C4B6;
flex-wrap: wrap; /* Allows wrapping of elements on small screens */
}
#controls select, #controls button {
margin: 5px;
font-size: 14px;
}
@media (max-width: 600px) {
#map {
height: 50vh; /* For mobile screens, reduce map height */
}
#controls {
flex-direction: column; /* Stack controls vertically on smaller screens */
}
#controls select, #controls button {
width: 100%; /* Make controls fill the available width */
margin: 8px 0; /* Add vertical margin for better spacing */
}
}
</style>
</head>
<body>
<div id="controls">
<select id="source">
<option value="">Select Source</option>
</select>
<select id="destination">
<option value="">Select Destination</option>
</select>
<button onclick="startRouteAnimation()">Animate Route</button>
<button onclick="animateAllLocations()">Animate All Locations</button>
<button onclick="stopAnimation()">Stop Animation</button>
</div>
<div id="map"></div>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<script>
const coordinates = {
"Uttara North": [23.869066, 90.367445],
"Uttara Center": [23.860118, 90.365106],
"Uttara South": [23.845934, 90.363175],
"Pallabi": [23.82619516961383, 90.36481554252525],
"Mirpur 11": [23.819438208310213, 90.36528532902963],
"Mirpur 10": [23.808582994847285, 90.36821595330717],
"Kazipara": [23.800017952100532, 90.37178261495391],
"Shewrapara": [23.79070140857881, 90.37564622631841],
"Agargaon": [23.778385546736345, 90.3800557456356],
"Bijoy Sarani": [23.766638127271825, 90.38307537134754],
"Farmgate": [23.75923604938459, 90.38694218434738],
"Kawran Bazar": [23.751392319539104, 90.39275707447003],
"Shahbagh": [23.740324209546923, 90.39600784811131],
"Dhaka University": [23.732091083122114, 90.39659408796354],
"Bangladesh Secretariat": [23.73004754106779, 90.40764881366906],
"Motijheel": [23.72816566933198, 90.41923497972823],
"Kamalapur": [23.732367758919807, 90.42547378971085]
};
const map = L.map('map').setView([23.8103, 90.4125], 12); // Centered on Dhaka
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: 'Β© OpenStreetMap contributors'
}).addTo(map);
// Populate source and destination dropdowns
const sourceSelect = document.getElementById('source');
const destinationSelect = document.getElementById('destination');
for (const location in coordinates) {
const option = document.createElement('option');
option.value = location;
option.textContent = location;
sourceSelect.appendChild(option);
destinationSelect.appendChild(option.cloneNode(true));
}
const markers = {};
for (const [name, coord] of Object.entries(coordinates)) {
const marker = L.marker(coord).addTo(map).bindPopup(`<b>${name}</b>`);
markers[name] = marker;
}
let currentIndex = 0;
const markerArray = Object.values(markers);
let animationTimeout; // Store the timeout ID to cancel animation
function getIntermediateNodes(source, destination) {
const allLocations = Object.keys(coordinates);
const sourceIndex = allLocations.indexOf(source);
const destinationIndex = allLocations.indexOf(destination);
const route = [];
if (sourceIndex < destinationIndex) {
// Forward direction (source to destination)
route.push(...allLocations.slice(sourceIndex, destinationIndex + 1));
} else {
// Reverse direction (destination to source)
route.push(...allLocations.slice(destinationIndex, sourceIndex + 1).reverse());
}
return route;
}
function startRouteAnimation() {
const source = sourceSelect.value;
const destination = destinationSelect.value;
if (!source || !destination) {
alert('Please select both source and destination locations.');
return;
}
const route = getIntermediateNodes(source, destination);
let routeIndex = 0;
function animateRoute() {
if (routeIndex >= route.length) {
return; // Animation completed
}
const currentLocation = route[routeIndex];
const marker = markers[currentLocation];
if (routeIndex === 0) {
map.flyTo(marker.getLatLng(), 14, { duration: 2 });
marker.openPopup();
} else {
setTimeout(() => {
map.flyTo(marker.getLatLng(), 14, { duration: 2 });
marker.openPopup();
}, 3000);
}
routeIndex++;
animationTimeout = setTimeout(animateRoute, 3000); // Wait before moving to the next
}
animateRoute();
}
function animateAllLocations() {
if (currentIndex > 0) {
markerArray[currentIndex - 1].closePopup();
}
if (currentIndex < markerArray.length) {
const marker = markerArray[currentIndex];
map.flyTo(marker.getLatLng(), 14, { duration: 2 });
marker.openPopup();
currentIndex++;
animationTimeout = setTimeout(animateAllLocations, 3000); // Wait 3 seconds before next
} else {
currentIndex = 0; // Restart animation
}
}
function stopAnimation() {
clearTimeout(animationTimeout); // Stop the timeout for animation
currentIndex = 0; // Reset index
for (const marker of markerArray) {
marker.closePopup(); // Close all popups
}
map.setView([23.8103, 90.4125], 12); // Reset map to initial view
sourceSelect.value = ''; // Clear source dropdown
destinationSelect.value = ''; // Clear destination dropdown
}
</script>
</body>
</html>
"""
components.html(map_html, height=600)