Falytom logoFALYTOM
Games
ToolsUI ComponentsServicesProductsAbout
LoginSign Up
menu
  1. Home
  2. /Web Development
  3. /Html
  4. /Geolocation Api
Your Progress0%
0 of 76 completed

Topics

Getting Started

  • What is HTML?
  • How the Web Works
  • Setting Up Your Environment
  • Your First HTML Page

HTML Document Structure

  • The DOCTYPE Declaration
  • The HTML Element
  • The Head Section
  • Meta Tags
  • The Body Element
  • HTML Comments

Text and Formatting

  • Headings (h1-h6)
  • Paragraphs
  • Line Breaks and Horizontal Rules
  • Text Formatting (Bold, Italic, etc.)
  • Quotations and Citations
  • Preformatted Text and Code
  • Subscript and Superscript

Links and Navigation

  • Creating Links
  • Absolute vs Relative URLs
  • Link Targets and Attributes
  • Email and Phone Links
  • Internal Page Links

Images and Media

  • Adding Images
  • Image Attributes
  • Image Formats
  • Figure and Figcaption
  • Responsive Images
  • Audio Elements
  • Video Elements
  • Embedding Content

Lists

  • Unordered Lists
  • Ordered Lists
  • Description Lists
  • Nested Lists

Tables

  • Table Basics
  • Table Headers and Footers
  • Spanning Columns and Rows
  • Table Captions
  • Styling Tables

Forms - Part 1 (Basics)

  • Introduction to Forms
  • Text Input Fields
  • Labels and Placeholders
  • Textarea Element
  • Checkboxes
  • Radio Buttons

Forms - Part 2 (Advanced)

  • Select Dropdowns
  • File Upload Inputs
  • HTML5 Input Types
  • Form Validation
  • Form Buttons
  • Fieldsets and Legends
  • Form Accessibility

Semantic HTML

  • What is Semantic HTML?
  • Header and Footer
  • Nav Element
  • Main and Article
  • Section and Aside
  • Div vs Semantic Elements
  • Time and Mark Elements

HTML5 Features

  • HTML5 Overview
  • Canvas Element
  • SVG in HTML
  • Geolocation API
  • Drag and Drop
  • Local Storage
  • Web Workers

Web Accessibility

  • Introduction to Accessibility
  • ARIA Attributes
  • Keyboard Navigation
  • Alt Text Best Practices
  • Color Contrast and Typography
  • Testing for Accessibility

Best Practices & SEO

  • HTML Best Practices
  • SEO Fundamentals
  • Meta Tags for SEO
  • Structured Data

Geolocation API

Access user location data with JavaScript

The Geolocation API is a powerful HTML5 feature that allows web applications to access the user's geographical location. With user permission, you can determine where someone is browsing from and create location-aware experiences.

What is the Geolocation API?

The Geolocation API provides JavaScript methods to retrieve a user's current position using their device's GPS, Wi-Fi, IP address, or cell tower triangulation. This enables you to build applications that can:

  • Show nearby stores or restaurants
  • Provide location-based weather information
  • Display maps centered on the user's location
  • Calculate distances and provide directions
  • Tag photos with location data

Browser Support and Privacy

The Geolocation API is well-supported in all modern browsers. However, there are important considerations:

  • User Permission Required: Browsers always ask for explicit permission before sharing location data
  • HTTPS Only: Most browsers require your site to use HTTPS to access geolocation (except on localhost)
  • Privacy First: Users can deny or revoke permission at any time

Basic Usage

The Geolocation API is accessed through the navigator.geolocation object. Here's a simple example:

geolocation-basic.js
if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(
    function(position) {
      // Success callback
      console.log("Latitude:", position.coords.latitude);
      console.log("Longitude:", position.coords.longitude);
    },
    function(error) {
      // Error callback
      console.error("Error:", error.message);
    }
  );
} else {
  console.log("Geolocation is not supported by this browser.");
}

Understanding the Position Object

When location is successfully retrieved, the Position object contains useful information:

position-properties.js
navigator.geolocation.getCurrentPosition(function(position) {
  // Coordinates object
  const coords = position.coords;
  
  console.log("Latitude:", coords.latitude);
  console.log("Longitude:", coords.longitude);
  console.log("Accuracy (meters):", coords.accuracy);
  console.log("Altitude (meters):", coords.altitude); // May be null
  console.log("Altitude accuracy:", coords.altitudeAccuracy); // May be null
  console.log("Heading (degrees):", coords.heading); // May be null
  console.log("Speed (m/s):", coords.speed); // May be null
  
  // Timestamp
  console.log("Timestamp:", position.timestamp);
});

Handling Errors

Always implement error handling to provide a good user experience when location access fails:

error-handling.js
navigator.geolocation.getCurrentPosition(
  function(position) {
    showLocation(position);
  },
  function(error) {
    switch(error.code) {
      case error.PERMISSION_DENIED:
        console.log("User denied location access");
        break;
      case error.POSITION_UNAVAILABLE:
        console.log("Location information unavailable");
        break;
      case error.TIMEOUT:
        console.log("Location request timed out");
        break;
      default:
        console.log("An unknown error occurred");
    }
  }
);

Geolocation Options

You can pass an options object to customize how location is retrieved:

options.js
const options = {
  enableHighAccuracy: true, // Use GPS if available
  timeout: 5000,            // Wait max 5 seconds
  maximumAge: 0             // Don't use cached position
};

navigator.geolocation.getCurrentPosition(
  successCallback,
  errorCallback,
  options
);

Watching Position Changes

For applications that need continuous location updates (like navigation), use watchPosition():

watch-position.js
let watchId = navigator.geolocation.watchPosition(
  function(position) {
    console.log("New position:", position.coords.latitude, position.coords.longitude);
    updateMap(position);
  },
  function(error) {
    console.error("Watch error:", error);
  },
  { enableHighAccuracy: true }
);

// Stop watching when no longer needed
function stopTracking() {
  navigator.geolocation.clearWatch(watchId);
  console.log("Stopped watching position");
}

Practical Example

Here's a complete example that displays the user's location:

location-display.html
<!DOCTYPE html>
<html>
<head>
  <title>My Location</title>
</head>
<body>
  <h1>Where Am I?</h1>
  <button id="findMe">Find My Location</button>
  <p id="status"></p>
  <p id="location"></p>

  <script>
    const findMeBtn = document.getElementById('findMe');
    const status = document.getElementById('status');
    const location = document.getElementById('location');

    findMeBtn.addEventListener('click', function() {
      if (!navigator.geolocation) {
        status.textContent = 'Geolocation is not supported';
        return;
      }

      status.textContent = 'Locating...';

      navigator.geolocation.getCurrentPosition(
        function(position) {
          const lat = position.coords.latitude;
          const lon = position.coords.longitude;
          const accuracy = position.coords.accuracy;

          status.textContent = '';
          location.textContent = 
            `Latitude: ${lat.toFixed(6)}° 
            Longitude: ${lon.toFixed(6)}° 
            (±${accuracy.toFixed(0)}m)`;
        },
        function(error) {
          status.textContent = 'Unable to retrieve location: ' + error.message;
        }
      );
    });
  </script>
</body>
</html>

Best Practices

  • Ask Permission Thoughtfully: Only request location when necessary and explain why you need it
  • Handle Errors Gracefully: Provide fallback options if location is unavailable
  • Respect Privacy: Don't store or share location data without consent
  • Consider Battery: High accuracy mode and position watching drain battery faster
  • Use Appropriate Accuracy: Don't use enableHighAccuracy if approximate location is sufficient
  • Cache When Appropriate: Use maximumAge to reduce unnecessary location requests

Key Takeaways

  • The Geolocation API provides access to user location through navigator.geolocation
  • User permission is always required to access location data
  • Use getCurrentPosition() for one-time location requests
  • Use watchPosition() for continuous location updates
  • Always implement error handling for better user experience
  • HTTPS is required on most browsers (except localhost)
  • The Position object provides coordinates, accuracy, and more

What's Next?

Now that you understand the Geolocation API, you can create location-aware web applications. In the next lesson, we'll explore drag and drop functionality, another powerful HTML5 feature for interactive user interfaces.

Know someone who'd find this guide helpful? Please share!

Previous
SVG in HTML
Next
Drag and Drop

Never Miss a New HTML Tutorial

Join 1,000+ developers learning HTML step-by-step. Get new tutorials, tips, and exclusive resources delivered to your inbox - completely FREE.

You might also like

UI Components

Ready-made components for your projects

Developer Tools

Boost productivity with handy generators

HTML Game

Learn HTML concepts through interactive gameplay

Join Our Web Development Training Program

Master frontend & backend development with hands-on projects.

Menu

Topics

Getting Started

  • What is HTML?
  • How the Web Works
  • Setting Up Your Environment
  • Your First HTML Page

HTML Document Structure

  • The DOCTYPE Declaration
  • The HTML Element
  • The Head Section
  • Meta Tags
  • The Body Element
  • HTML Comments

Text and Formatting

  • Headings (h1-h6)
  • Paragraphs
  • Line Breaks and Horizontal Rules
  • Text Formatting (Bold, Italic, etc.)
  • Quotations and Citations
  • Preformatted Text and Code
  • Subscript and Superscript

Links and Navigation

  • Creating Links
  • Absolute vs Relative URLs
  • Link Targets and Attributes
  • Email and Phone Links
  • Internal Page Links

Images and Media

  • Adding Images
  • Image Attributes
  • Image Formats
  • Figure and Figcaption
  • Responsive Images
  • Audio Elements
  • Video Elements
  • Embedding Content

Lists

  • Unordered Lists
  • Ordered Lists
  • Description Lists
  • Nested Lists

Tables

  • Table Basics
  • Table Headers and Footers
  • Spanning Columns and Rows
  • Table Captions
  • Styling Tables

Forms - Part 1 (Basics)

  • Introduction to Forms
  • Text Input Fields
  • Labels and Placeholders
  • Textarea Element
  • Checkboxes
  • Radio Buttons

Forms - Part 2 (Advanced)

  • Select Dropdowns
  • File Upload Inputs
  • HTML5 Input Types
  • Form Validation
  • Form Buttons
  • Fieldsets and Legends
  • Form Accessibility

Semantic HTML

  • What is Semantic HTML?
  • Header and Footer
  • Nav Element
  • Main and Article
  • Section and Aside
  • Div vs Semantic Elements
  • Time and Mark Elements

HTML5 Features

  • HTML5 Overview
  • Canvas Element
  • SVG in HTML
  • Geolocation API
  • Drag and Drop
  • Local Storage
  • Web Workers

Web Accessibility

  • Introduction to Accessibility
  • ARIA Attributes
  • Keyboard Navigation
  • Alt Text Best Practices
  • Color Contrast and Typography
  • Testing for Accessibility

Best Practices & SEO

  • HTML Best Practices
  • SEO Fundamentals
  • Meta Tags for SEO
  • Structured Data
Falytom logoFALYTOM

Learn technologies like HTML, CSS, JavaScript, React, NodeJS and more through interactive games, tutorials, components and free tools. Transform your businesses with AI chatbots, SEO-optimized websites, and professional development services.

© 2025 Tomilola Group
  • Facebook logo
  • Twitter logo
  • Instagram logo
  • LinkedIn logo
  • GitHub logo
  • YouTube logo