44 lines
1.5 KiB
JavaScript
44 lines
1.5 KiB
JavaScript
function getCoordinates() {
|
|
return new Promise((resolve, reject) => {
|
|
if (navigator.geolocation) {
|
|
navigator.geolocation.getCurrentPosition(
|
|
position => resolve(position.coords),
|
|
error => reject(error)
|
|
);
|
|
} else {
|
|
reject(new Error("Geolocation is not supported by this browser."));
|
|
}
|
|
});
|
|
}
|
|
|
|
async function getCity() {
|
|
try {
|
|
const coords = await getCoordinates();
|
|
const response = await fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${coords.latitude}&lon=${coords.longitude}`);
|
|
const data = await response.json();
|
|
|
|
if (data && data.address) {
|
|
const city = data.address.city || data.address.town || data.address.village || data.address.hamlet;
|
|
const postalCode = data.address.postcode;
|
|
return postalCode + ' ' + city || '';
|
|
}
|
|
} catch {
|
|
return '';
|
|
}
|
|
}
|
|
|
|
async function getLocation() {
|
|
try {
|
|
const coords = await getCoordinates();
|
|
const response = await fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${coords.latitude}&lon=${coords.longitude}`);
|
|
const data = await response.json();
|
|
|
|
if (data && data.address) {
|
|
const city = data.address.city || data.address.town || data.address.village || data.address.hamlet;
|
|
const postalCode = data.address.postcode;
|
|
return { postalCode: postalCode, city: city };
|
|
}
|
|
} catch {
|
|
return { postalCode: '', city: '' };
|
|
}
|
|
} |