// app.js - Modern, idiot-proof, client-only (Overpass + Leaflet) // Features: Dark mode toggle (persist), caching (5 min), top-5 list, multiple Overpass endpoints fallback // --- UI elements const findBtn = document.getElementById('findBtn'); const resetBtn = document.getElementById('resetBtn'); const statusEl = document.getElementById('status'); const outputEl = document.getElementById('output'); const themeSwitch = document.getElementById('themeSwitch'); // --- Map state let map, userMarker, shopMarker; // --- Overpass endpoints fallback (CORS-friendly mirrors) const OVERPASS_ENDPOINTS = [ 'https://overpass-api.de/api/interpreter', 'https://overpass.kumi.systems/api/interpreter', 'https://lz4.overpass-api.de/api/interpreter' ]; // --- small helpers function setStatus(txt) { statusEl.textContent = txt; } function showHTML(html) { outputEl.innerHTML = html; outputEl.style.display = 'block'; } function clearOutput() { outputEl.innerHTML = ''; outputEl.style.display = 'none'; } function roundCoord(x){ return Math.round(x*10000)/10000; } // for cache key // --- caching: simple localStorage cache (keyed by rounded coords) // stores { ts: timestamp_ms, payload: {...} } const CACHE_TTL = 1000 * 60 * 5; // 5 minutes function getCacheKey(lat, lon, radius=3000){ return `osm_nearest_${roundCoord(lat)}_${roundCoord(lon)}_${radius}`;} function readCache(key){ try { const s = localStorage.getItem(key); if(!s) return null; const obj = JSON.parse(s); if(Date.now() - obj.ts > CACHE_TTL) { localStorage.removeItem(key); return null; } return obj.payload; } catch(e){ return null; } } function writeCache(key, payload){ try { localStorage.setItem(key, JSON.stringify({ ts: Date.now(), payload })); } catch(e){} } // --- haversine distance (meters) function haversine(lat1, lon1, lat2, lon2){ const R = 6371e3; const toRad = d => d * Math.PI / 180; const φ1 = toRad(lat1), φ2 = toRad(lat2); const Δφ = toRad(lat2 - lat1), Δλ = toRad(lon2 - lon1); const a = Math.sin(Δφ/2)**2 + Math.cos(φ1)*Math.cos(φ2)*Math.sin(Δλ/2)**2; return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); } // --- build Overpass QL function buildQuery(lat, lon, radius=3000, maxResults=30){ return ` [out:json][timeout:25]; ( node["shop"~"supermarket|grocery|convenience"](around:${radius},${lat},${lon}); way["shop"~"supermarket|grocery|convenience"](around:${radius},${lat},${lon}); relation["shop"~"supermarket|grocery|convenience"](around:${radius},${lat},${lon}); ); out center ${maxResults}; `; } // --- try endpoints sequentially async function queryOverpass(query){ let lastError = null; for(const ep of OVERPASS_ENDPOINTS){ try { console.log('Trying Overpass endpoint:', ep); const resp = await fetch(ep, { method: 'POST', headers: { 'Content-Type': 'text/plain' }, body: query, mode: 'cors' }); if(!resp.ok){ const t = await resp.text().catch(()=>null); lastError = { endpoint: ep, status: resp.status, text: t }; console.warn('Overpass returned non-OK', lastError); continue; } const data = await resp.json(); return { data, endpoint: ep }; } catch(err){ lastError = { endpoint: ep, message: err.message || String(err) }; console.warn('Overpass fetch error', lastError); continue; } } const e = new Error('All Overpass endpoints failed'); e.details = lastError; throw e; } // --- map helpers function initMap(lat=20, lon=0, zoom=2){ if(!map){ map = L.map('map', { zoomControl:true, attributionControl: true }).setView([lat, lon], zoom); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19 }).addTo(map); } else { map.setView([lat, lon], zoom); } } function setMarkers(userLat, userLon, shopLat, shopLon, shopName){ if(userMarker) userMarker.remove(); if(shopMarker) shopMarker.remove(); userMarker = L.marker([userLat, userLon]).addTo(map).bindPopup('You are here').openPopup(); shopMarker = L.marker([shopLat, shopLon]).addTo(map).bindPopup(shopName || 'Supermarket'); const bounds = L.latLngBounds([[userLat, userLon],[shopLat, shopLon]]); map.fitBounds(bounds.pad(0.2)); } // --- main search flow async function findNearest(){ clearOutput(); setStatus('Requesting your location — please allow location access.'); if(!navigator.geolocation){ setStatus('Geolocation not supported by your browser.'); return; } navigator.geolocation.getCurrentPosition(async pos=>{ const lat = pos.coords.latitude; const lon = pos.coords.longitude; const radius = 3000; setStatus(`Location acquired: ${lat.toFixed(5)}, ${lon.toFixed(5)} — searching within ${radius} m...`); initMap(lat, lon, 15); const cacheKey = getCacheKey(lat, lon, radius); const cached = readCache(cacheKey); if(cached){ setStatus(`Using cached result (${Math.round((cached.sourceAge||0)/1000)}s ago).`); renderResults(cached.payload, lat, lon); return; } const q = buildQuery(lat, lon, radius, 40); try { const { data, endpoint } = await queryOverpass(q); if(!data || !Array.isArray(data.elements) || data.elements.length === 0){ setStatus('No supermarkets found within radius. Try increasing radius or moving closer to shops.'); showHTML(`