import React, { useState, useEffect } from 'react'; import { mosdokFetch } from '../../apiFetch'; // Haversine formula to calculate distance between two coordinates const calculateDistance = (lat1, lon1, lat2, lon2) => { const R = 6371; // Earth's radius in kilometers const dLat = (lat2 - lat1) * Math.PI / 180; const dLon = (lon2 - lon1) * Math.PI / 180; const a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.sin(dLon/2) * Math.sin(dLon/2); const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return R * c; // Distance in kilometers }; export default function LegkozelebbiMosdo() { const [nearestRestroom, setNearestRestroom] = useState(null); const [userLocation, setUserLocation] = useState(null); const [error, setError] = useState(null); const [loading, setLoading] = useState(false); const findNearestRestroom = async (latitude, longitude) => { setLoading(true); try { // Fetch restrooms from the API const mosdok = await mosdokFetch(); // Find the nearest restroom let nearest = null; let minDistance = Infinity; mosdok.forEach(mosdo => { // Use hossz_koord and szel_koord instead of latitude/longitude if (mosdo.hossz_koord && mosdo.szel_koord) { const distance = calculateDistance( latitude, longitude, mosdo.szel_koord, mosdo.hossz_koord ); if (distance < minDistance) { minDistance = distance; nearest = mosdo; } } }); if (nearest) { // Add the calculated distance to the nearest restroom object nearest.distanceKm = minDistance.toFixed(2); setNearestRestroom(nearest); } else { setError("Nem találtunk elérhető mosdót a közelben."); } } catch (err) { setError("Hiba történt a mosdók lekérésekor."); console.error(err); } finally { setLoading(false); } }; const handleLocationPermission = () => { if ("geolocation" in navigator) { setLoading(true); navigator.geolocation.getCurrentPosition( (position) => { const { latitude, longitude } = position.coords; setUserLocation({ latitude, longitude }); findNearestRestroom(latitude, longitude); }, (error) => { setError("Nem sikerült lekérni a tartózkodási helyét: " + error.message); setLoading(false); } ); } else { setError("A helymeghatározás nem elérhető a böngészőben."); } }; // Render loading state if (loading) { return (
Kerület: {nearestRestroom.kerulet}
Legközelebbi megálló: {nearestRestroom.kozeli_megall}
Ár: {nearestRestroom.ar} Ft
Nyitvatartás: {nearestRestroom.nyitva}
ÚtvonaltervEngedélyezed a helyzetmeghatározást?