96 lines
2.6 KiB
JavaScript
96 lines
2.6 KiB
JavaScript
const axios = require("axios");
|
|
|
|
// Funzione principale
|
|
async function loc(lng, lat) {
|
|
const primary = await place(lng, lat); // Geoapify
|
|
const fallback = await placePhoton(lng, lat); // Photon
|
|
|
|
// Se Geoapify fallisce → usa Photon
|
|
if (!primary) return fallback;
|
|
|
|
// Se Geoapify manca city → prendi da Photon
|
|
if (!primary.city && fallback?.city) {
|
|
primary.city = fallback.city;
|
|
}
|
|
|
|
// Se Geoapify manca postcode → prendi da Photon
|
|
if (!primary.postcode && fallback?.postcode) {
|
|
primary.postcode = fallback.postcode;
|
|
}
|
|
|
|
// Se Geoapify manca address → prendi da Photon
|
|
if (!primary.address && fallback?.address) {
|
|
primary.address = fallback.address;
|
|
}
|
|
|
|
// Se Geoapify manca region → prendi da Photon
|
|
if (!primary.region && fallback?.region) {
|
|
primary.region = fallback.region;
|
|
}
|
|
|
|
// Se Geoapify manca county_code → Photon NON lo fornisce
|
|
// quindi non possiamo riempirlo
|
|
|
|
return primary;
|
|
}
|
|
|
|
// Geoapify (sorgente principale)
|
|
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: k?.country || undefined,
|
|
region: k?.state || undefined,
|
|
postcode: k?.postcode || undefined,
|
|
city: k?.city || undefined,
|
|
county_code: k?.county_code || undefined,
|
|
address: k?.address_line1 || undefined,
|
|
timezone: k?.timezone?.name || undefined,
|
|
time: k?.timezone?.offset_STD || undefined
|
|
};
|
|
|
|
} catch (err) {
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
// Photon (fallback)
|
|
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, // Photon non lo fornisce
|
|
country: p.country || undefined,
|
|
region: p.state || undefined,
|
|
postcode: p.postcode || undefined,
|
|
city: p.city || p.town || p.village || undefined,
|
|
county_code: undefined, // Photon non fornisce codici ISO
|
|
address: p.street ? `${p.street} ${p.housenumber || ""}`.trim() : undefined,
|
|
timezone: undefined,
|
|
time: undefined
|
|
};
|
|
|
|
} catch (err) {
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
module.exports = loc;
|