101 lines
3.0 KiB
HTML
101 lines
3.0 KiB
HTML
<!doctype html>
|
|
<html lang="de">
|
|
<head>
|
|
<meta charset="UTF-8" />
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
<title>GeoLocation API auslesen</title>
|
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
|
|
</head>
|
|
<body>
|
|
<main>
|
|
<div class="container py-5">
|
|
<h1>GeoLocation API auslesen</h1>
|
|
</div>
|
|
</main>
|
|
<script>
|
|
'use strict';
|
|
|
|
(() => {
|
|
// === DOM & VARS =======
|
|
const DOM = {};
|
|
|
|
// === INIT =============
|
|
const init = () => {
|
|
getGeoLocation().then((dataGeolocation) => {
|
|
// console.log('Geo Location:' + dataGeolocation);
|
|
console.log(setGeoLocation(dataGeolocation));
|
|
// getWeather().then((data) => {
|
|
// console.log('Weather Data:' + data);
|
|
// setWeather(data);
|
|
// });
|
|
});
|
|
|
|
getCoordinates().then((data) => {
|
|
console.log(data);
|
|
});
|
|
};
|
|
|
|
// === EVENTHANDLER =====
|
|
|
|
// === XHR/FETCH ========
|
|
|
|
// === FUNCTIONS ========
|
|
const setGeoLocation = (data) => {
|
|
const { longitude, latitude } = data;
|
|
console.log(`LON: ${data.longitude} LAT: ${data.latitude}`);
|
|
return { longitude, latitude };
|
|
};
|
|
|
|
const getGeoLocation = async () => {
|
|
try {
|
|
const res = await fetch('https://myiprightnow.com/api/ip');
|
|
if (!res.ok) {
|
|
throw Error('Fetch Error Geolocation');
|
|
}
|
|
const data = await res.json();
|
|
console.log(data);
|
|
return data;
|
|
} catch (error) {
|
|
console.error(error);
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
const getCoordinates = () => {
|
|
return new Promise((resolve, reject) => {
|
|
// Prüfen, ob der Browser Geolocation unterstützt
|
|
if (!navigator.geolocation) {
|
|
reject(new Error('Geolocation wird von diesem Browser nicht unterstützt.'));
|
|
return;
|
|
}
|
|
|
|
// Optionen für die Abfrage (optional)
|
|
const options = {
|
|
enableHighAccuracy: true, // Bestmögliche Genauigkeit erzwingen
|
|
timeout: 5000, // Max. Wartezeit in Millisekunden
|
|
maximumAge: 0, // Kein Cache, frische Daten anfordern
|
|
};
|
|
|
|
// Erfolg-Callback
|
|
const success = (position) => {
|
|
const { latitude, longitude } = position.coords;
|
|
resolve({ latitude, longitude });
|
|
};
|
|
|
|
// Fehler-Callback
|
|
const error = (err) => {
|
|
reject(new Error(`Standortabfrage fehlgeschlagen: ${err.message}`));
|
|
};
|
|
|
|
// API-Aufruf starten
|
|
// https://developer.mozilla.org/de/docs/Web/API/Geolocation/getCurrentPosition
|
|
navigator.geolocation.getCurrentPosition(success, error, options);
|
|
});
|
|
};
|
|
|
|
init();
|
|
})();
|
|
</script>
|
|
</body>
|
|
</html>
|