<header>
  <h2 class="title">Geolocation -> heading</h2>
  <p class="description">Отримує напрямок руху користувача і відображає його на сторінці в реальному часі.</p>
</header>
<main>
  <div class="result">
    <button id="getHeadingBtn">Отримати напрямок руху</button>
    <p id="headingOutput">Напрямок: не доступний</p>
    <p>Оновлення напряму: <span id="updateInterval">1</span> сек.</p>
  </div>
</main>
body {
  font-size: 16px;
  line-height: 1.5;
  font-family: monospace;
}

header {
  background-color: #f1f1f1;
  margin-bottom: 25px;
  padding: 15px;
  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;
  box-shadow: 0px 0px 3px 0px rgba(118, 118, 118, 1);
}

button {
  background-color: #4CAF50;
  color: white;
  padding: 10px 20px;
  border: none;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}

p {
  font-size: 18px;
  color: #333;
}
let watchID = null;

// Функція для отримання напрямку руху
function startTracking() {
  if (navigator.geolocation) {
    // Використовуємо getCurrentPosition або watchPosition для постійного отримання оновлень
    watchID = navigator.geolocation.watchPosition(function(position) {
      // Отримуємо напрямок руху (в градусах відносно півночі)
      const heading = position.coords.heading;

      // Виводимо напрямок на екран
      const headingElement = document.getElementById('headingOutput');
      if (heading !== null) {
        headingElement.textContent = `Напрямок: ${heading.toFixed(2)}°`;
      } else {
        headingElement.textContent = 'Напрямок: не визначено';
      }
    }, function(error) {
      console.error('Помилка геолокації:', error);
    }, {
      enableHighAccuracy: true,
      maximumAge: 0,
      timeout: 5000
    });
  } else {
    alert('Геолокація не підтримується цим браузером.');
  }
}

// Функція для зупинки відстеження
function stopTracking() {
  if (watchID !== null) {
    navigator.geolocation.clearWatch(watchID);
    watchID = null;
  }
}

// Додавання обробника для кнопки
document.getElementById('getHeadingBtn').addEventListener('click', function() {
  if (watchID === null) {
    startTracking();
    this.textContent = 'Зупинити відстеження';
  } else {
    stopTracking();
    this.textContent = 'Отримати напрямок руху';
  }
});

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.