Below are the distances between the parent user's location and the existing locations in the database.
<div id="distances">
Loading distances...
</div>
<script>
// Function to fetch distances from the server
function fetchDistances() {
fetch('http://127.0.0.1:5000/calculate-distances')
.then(response => response.json())
.then(data => {
const distancesDiv = document.getElementById('distances');
distancesDiv.innerHTML = ''; // Clear any existing content
if (data.error) {
distancesDiv.innerHTML = `<p style="color:red;">Error: ${data.error}</p>`;
} else if (data.length === 0) {
distancesDiv.innerHTML = '<p>No locations found.</p>';
} else {
data.forEach(item => {
distancesDiv.innerHTML += `
<div class="distance-item">
<strong>Location:</strong> ${item.name} <br>
<strong>Distance:</strong> ${item.distance.toFixed(2)} km
</div>
`;
});
}
})
.catch(error => {
console.error('Error fetching distances:', error);
document.getElementById('distances').innerHTML = '<p style="color:red;">Failed to load distances. Please try again later.</p>';
});
}
// Fetch distances on page load
window.onload = fetchDistances;
</script>
from flask import Flask, jsonify import mysql.connector from math import radians, sin, cos, sqrt, asin
app = Flask(name)
def get_db_connection(): return mysql.connector.connect( host='localhost', database='geolocation_db', user='root', password='root_password' )
def haversine(lat1, lon1, lat2, lon2): R = 6371 # Radius of Earth in kilometers dlat = radians(lat2 - lat1) dlon = radians(lon2 - lon1) a = sin(dlat / 2) ** 2 + cos(radians(lat1)) * cos(radians(lat2)) * sin(dlon / 2) ** 2 c = 2 * asin(sqrt(a)) return R * c
def get_parent_geolocation(): try: conn = get_db_connection() cursor = conn.cursor(dictionary=True) cursor.execute("SELECT latitude, longitude FROM users WHERE id = 1") # Assuming the parent user has an ID of 1 parent_location = cursor.fetchone() return parent_location['latitude'], parent_location['longitude'] except mysql.connector.Error as err: return None, None finally: cursor.close() conn.close()
def get_existing_locations(): try: conn = get_db_connection() cursor = conn.cursor(dictionary=True) cursor.execute("SELECT name, latitude, longitude FROM locations") locations = cursor.fetchall() return locations except mysql.connector.Error as err: return [] finally: cursor.close() conn.close()
@app.route('/calculate-distances', methods=['GET']) def calculate_distances(): parent_lat, parent_lon = get_parent_geolocation()
if parent_lat is None or parent_lon is None:
return jsonify({"error": "Could not retrieve parent user's geolocation"}), 500
existing_locations = get_existing_locations()
distances = []
for location in existing_locations:
distance = haversine(parent_lat, parent_lon, location['latitude'], location['longitude'])
distances.append({
'name': location['name'],
'distance': distance
})
return jsonify(distances)
if name == 'main': app.run(debug=True)