πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
Search courses…
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

Geolocation API

Web Foundations🟒 Free Lesson

Advertisement

Geolocation API

Location services, maps integration, and location-based features.

Overview

Geolocation provides user location data for location-based features.

Key Concepts

  • getCurrentPosition β€” Get current location
  • watchPosition β€” Track location changes
  • Permission β€” User must grant access
  • Accuracy β€” GPS, WiFi, cell tower based
  • Privacy β€” Respect user privacy

Code Examples

<button id="getLocation">Get My Location</button>
<div id="map" style="width: 100%; height: 400px;"></div>

<script>
const mapDiv = document.getElementById('map');
let watchId;

document.getElementById('getLocation').addEventListener('click', () => {
  if (!navigator.geolocation) {
    alert('Geolocation not supported');
    return;
  }

  navigator.geolocation.getCurrentPosition(
    (position) => {
      const { latitude, longitude, accuracy } = position.coords;
      mapDiv.innerHTML = `
        <p>Latitude: ${latitude}</p>
        <p>Longitude: ${longitude}</p>
        <p>Accuracy: ${accuracy}m</p>
      `;
    },
    (error) => {
      switch(error.code) {
        case error.PERMISSION_DENIED:
          alert('Location access denied');
          break;
        case error.POSITION_UNAVAILABLE:
          alert('Location unavailable');
          break;
        case error.TIMEOUT:
          alert('Location request timed out');
          break;
      }
    },
    {
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 0
    }
  );
});

// Watch position
function startTracking() {
  watchId = navigator.geolocation.watchPosition(
    (position) => {
      console.log('Location updated:', position.coords);
    },
    (error) => console.error(error)
  );
}

function stopTracking() {
  navigator.geolocation.clearWatch(watchId);
}
</script>

Practice

Build a location-based weather app using the Geolocation API.

⭐

Premium Content

Geolocation API

Unlock this lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
πŸ’ΌInterview Prep
πŸ“œCertificates
🀝Community Access

Already a member? Log in

Need Expert Web Development Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement