Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

HTML5 Geolocation API | HTML Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. HTML Course

Lesson 30 of 55

·HTML

HTML5 Geolocation API

8 min

Course progress55%

What you'll learn

Keep these ideas in mind as you work through the lesson.

5 points
  • Using `navigator.geolocation.getCurrentPosition` to request location
  • Permission model and privacy considerations (HTTPS, user consent)
  • Error handling with the callback's error object
  • Graceful degradation for unsupported browsers or denied permission
  • Common use‑cases and best practices for privacy compliance

Getting User Location

The Geolocation API lets you request the user’s latitude and longitude (with permission).

<button id='locBtn'>Show My Location</button>
<div id='coords'></div>
<script>
  document.getElementById('locBtn').addEventListener('click', () => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(pos => {
        const { latitude, longitude } = pos.coords;
        document.getElementById('coords').textContent = `Lat: ${latitude}, Lon: ${longitude}`;
      }, err => {
        alert('Location error: ' + err.message);
      });
    } else {
      alert('Geolocation not supported');
    }
  });
</script>

Privacy & security

  • Browsers require HTTPS for Geolocation.
  • Users can grant or deny permission; always provide a fallback UI for those who deny or have unsupported browsers.
  • Do not store raw coordinates in plain text without user consent – respect privacy regulations (GDPR, CCPA).

Practical uses

  • Show nearby stores on a map.
  • Provide location‑specific content (weather, local news).
  • Auto‑fill address fields with a reverse‑geocoding service (server‑side).

Quick checklist for Geolocation

  1. Feature gated behind HTTPS? ✅
  2. Permission request handled gracefully (if (navigator.geolocation)) ? ✅
  3. Fallback UI/message for denied permission? ✅
  4. No raw coordinates stored without consent? ✅
  5. UI updates (e.g., showing coordinates) accessible? ✅

Tip: Pair the Geolocation API with a mapping library (Leaflet, Mapbox) for a richer user experience.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from HTML CourseBrowse activities
Previous lessonInternationalization – `lang` Attribute and Text DirectionContinue to lesson 31HTML5 Drag-and-Drop APIBack to HTML Course curriculum