const axios = require("axios"); async function loc(lng, lat) { const primary = await place(lng, lat); // Geoapify const fallback = await placePhoton(lng, lat); // Photon if (!primary) return fallback; if (!primary.city && fallback?.city) { primary.city = fallback.city; } if (!primary.postcode && fallback?.postcode) { primary.postcode = fallback.postcode; } if (!primary.address && fallback?.address) { primary.address = fallback.address; } if (!primary.region && fallback?.region) { primary.region = fallback.region; } if (!primary.country_code && fallback?.country_code) { primary.country_code = fallback.country_code; } if (!primary.county && fallback?.county) { primary.county = fallback.county; } if (!primary.county_code && fallback?.county_code) { primary.county_code = fallback.county_code; } return primary; } function normCountryCode(v) { if (!v) return undefined; const s = String(v).trim().toUpperCase(); return s.length ? s : undefined; } async function place(lng, lat) { const apiKey = "6dc7fb95a3b246cfa0f3bcef5ce9ed9a"; const url = `https://api.geoapify.com/v1/geocode/reverse?lat=${lat}&lon=${lng}&apiKey=${apiKey}`; try { const r = await axios.get(url); if (r.status !== 200) return undefined; if (!r.data.features || r.data.features.length === 0) return undefined; const k = r.data.features[0].properties; return { continent: k?.timezone?.name?.split("/")?.[0] || undefined, // Country / Paese country: k?.country || undefined, country_code: normCountryCode(k?.country_code), // County / contea county: k?.county || undefined, county_code: k?.county_code || undefined, // Regione / stato amministrativo region: k?.state || undefined, postcode: k?.postcode || undefined, city: k?.city || k?.town || k?.village || undefined, address: k?.address_line1 || undefined, timezone: k?.timezone?.name || undefined, time: k?.timezone?.offset_STD || undefined, }; } catch (err) { return undefined; } } async function placePhoton(lng, lat) { try { const url = `https://photon.patachina.it/reverse?lon=${lng}&lat=${lat}`; const r = await axios.get(url); if (!r.data || !r.data.features || r.data.features.length === 0) { return undefined; } const p = r.data.features[0].properties; return { continent: undefined, // Country / Paese country: p.country || undefined, country_code: normCountryCode(p.countrycode || p.country_code), // County / contea, se disponibile county: p.county || undefined, county_code: p.county_code || undefined, region: p.state || undefined, postcode: p.postcode || undefined, city: p.city || p.town || p.village || undefined, address: p.street ? `${p.street} ${p.housenumber || ""}`.trim() : undefined, timezone: undefined, time: undefined, }; } catch (err) { return undefined; } } module.exports = loc;