49 lines
1.2 KiB
TypeScript
49 lines
1.2 KiB
TypeScript
import memoize from 'memoizee';
|
|
|
|
export const _findAddress = async (
|
|
lon: number,
|
|
lat: number,
|
|
locale: () => string
|
|
) => {
|
|
try {
|
|
const response = await fetch(
|
|
`https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lon}&format=jsonv2&addressdetails=1&extratags=1&namedetails=1&accept-language=${locale()}`,
|
|
{ headers: { 'User-Agent': 'Dyomedea' } }
|
|
);
|
|
const data = await response.json();
|
|
console.log({ caller: 'findAddress', lon, lat, data });
|
|
return data;
|
|
} catch (error) {
|
|
console.error({ caller: 'findAddress', lon, lat, error });
|
|
return {};
|
|
}
|
|
};
|
|
|
|
export const findAddress = memoize(_findAddress, {
|
|
promise: true,
|
|
max: 1000,
|
|
maxAge: 36000000,
|
|
});
|
|
|
|
export const getVillageOrTown = (address: any) => {
|
|
const citySynonyms = [
|
|
'village',
|
|
'city',
|
|
'town',
|
|
'municipality',
|
|
'hamlet',
|
|
'suburb',
|
|
'locality',
|
|
];
|
|
|
|
if (!address || !address.address) return '';
|
|
|
|
for (let synonym of citySynonyms) {
|
|
// console.log({ caller: 'getVillageOrTown', address, synonym });
|
|
if (synonym in address?.address) {
|
|
return address?.address[synonym];
|
|
}
|
|
}
|
|
return address?.address?.country;
|
|
};
|