raomyousaf's picture
Update app.py
8ac37aa verified
import requests
import math
import streamlit as st
# Fetch vehicle coordinates from the API
def get_vehicle_coordinates():
url = "http://103.9.23.45/TrakkerServices/Api/Home/GetSOSLastLocation/SOSUser1/SOSPassword1/03300607077/null"
response = requests.get(url)
# Check if the response is successful
if response.status_code == 200:
data = response.json()
return data
else:
return None
# Haversine formula to calculate distance between two coordinates
def calculate_distance(coord1, coord2):
lat1, lon1 = coord1
lat2, lon2 = coord2
R = 6371 # Radius of the Earth in kilometers
phi1, phi2 = math.radians(lat1), math.radians(lat2)
delta_phi = math.radians(lat2 - lat1)
delta_lambda = math.radians(lon2 - lon1)
a = math.sin(delta_phi / 2)**2 + math.cos(phi1) * math.cos(phi2) * math.sin(delta_lambda / 2)**2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
distance = R * c # Resulting distance in kilometers
return distance
# Streamlit UI
st.title("Vehicle Distance Calculator")
# Fetch the vehicle data from the API
vehicle_data = get_vehicle_coordinates()
# Handle the case where data is not available
if vehicle_data is None:
st.error("Failed to fetch vehicle data.")
else:
# Assuming vehicle data has 'RegNo', 'latitude', and 'longitude' for each vehicle
vehicle_regnos = [vehicle['RegNo'] for vehicle in vehicle_data] # Extract vehicle registration numbers (RegNo)
# Select two vehicles from the list
selected_vehicle1 = st.selectbox("Select the first vehicle", vehicle_regnos)
selected_vehicle2 = st.selectbox("Select the second vehicle", vehicle_regnos)
# Retrieve the selected vehicle's data
vehicle1 = next(vehicle for vehicle in vehicle_data if vehicle['RegNo'] == selected_vehicle1)
vehicle2 = next(vehicle for vehicle in vehicle_data if vehicle['RegNo'] == selected_vehicle2)
# Extract coordinates of the selected vehicles
coord1 = (vehicle1['latitude'], vehicle1['longitude'])
coord2 = (vehicle2['latitude'], vehicle2['longitude'])
# Calculate the distance between the two vehicles
distance = calculate_distance(coord1, coord2)
# Display the calculated distance
st.write(f"The distance between vehicle {selected_vehicle1} and vehicle {selected_vehicle2} is {distance:.2f} km")