<header>
  <h2 class="title">Geolocation -> longitude</h2>
  <p class="description">Повертає довготу поточного місця користувача</p>
</header>
<main>
  <div class="result">
    <button id="get-location-btn">Отримати довготу</button>
    <label>
      <input type="checkbox" id="auto-update-toggle" />
      Автооновлення
    </label>
    <p id="longitude-display">Довгота: <span id="longitude">--</span></p>
  </div>
</main>
body {
  font-size: 16px;
  line-height: 1.5;
  font-family: monospace;
}

header {
  background-color: #f1f1f1;
  margin-bottom: 25px;
  padding: 15px;
  -webkit-box-shadow: 0px 0px 3px 0px rgba(118, 118, 118, 1);
  -moz-box-shadow: 0px 0px 3px 0px rgba(118, 118, 118, 1);
  box-shadow: 0px 0px 3px 0px rgba(118, 118, 118, 1);
}

header h2.title {
  padding-bottom: 15px;
  border-bottom: 1px solid #999;
}

header p.description {
  font-style: italic;
  color: #222;
}

.result {
  background-color: #f8f8f8;
  padding: 15px;
  -webkit-box-shadow: 0px 0px 3px 0px rgba(118, 118, 118, 1);
  -moz-box-shadow: 0px 0px 3px 0px rgba(118, 118, 118, 1);
  box-shadow: 0px 0px 3px 0px rgba(118, 118, 118, 1);
}

button {
  font-size: 14px;
  padding: 10px;
  margin-top: 10px;
}

label {
  display: inline-block;
  margin-top: 15px;
  font-size: 14px;
}

p {
  margin-top: 15px;
  font-size: 16px;
}
const longitudeDisplay = document.getElementById("longitude");
const autoUpdateToggle = document.getElementById("auto-update-toggle");
let watchId = null;

document.getElementById("get-location-btn").addEventListener("click", () => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        longitudeDisplay.textContent = position.coords.longitude.toFixed(6);
      },
      (error) => {
        alert("Не вдалося отримати геолокацію: " + error.message);
      }
    );
  } else {
    alert("Геолокація не підтримується вашим браузером.");
  }
});

autoUpdateToggle.addEventListener("change", (event) => {
  if (event.target.checked) {
    if (navigator.geolocation) {
      watchId = navigator.geolocation.watchPosition(
        (position) => {
          longitudeDisplay.textContent = position.coords.longitude.toFixed(6);
        },
        (error) => {
          alert("Не вдалося оновити геолокацію: " + error.message);
        },
        { enableHighAccuracy: true, timeout: 5000 }
      );
    }
  } else {
    navigator.geolocation.clearWatch(watchId);
    watchId = null;
  }
});

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.