javascript

Geolocation API in JavaScript

The Geolocation API allows a web application to access a user’s geographical location (latitude, longitude, and more), with the user’s permission. It’s commonly used for maps, ride-hailing apps, weather apps, delivery tracking, and location-based services.

If you want to break into tech without spending years in school, this intensive software development training in Abuja is built for you.

Key Things to Know First

  • Available via navigator.geolocation
  • Permission-based (the browser will ask the user)
  • Works only on secure contexts (https or localhost)
  • Supported by most modern browsers

Learn JavaScript online

Basic Syntax

navigator.geolocation.getCurrentPosition(success, error, options);

Parameters

  • success → function called when location is retrieved
  • error → function called if something goes wrong
  • options → optional settings (accuracy, timeout, cache)

Example 1: Get User’s Current Location

if ("geolocation" in navigator) {
  navigator.geolocation.getCurrentPosition(
    (position) => {
      const latitude = position.coords.latitude;
      const longitude = position.coords.longitude;

      console.log("Latitude:", latitude);
      console.log("Longitude:", longitude);
    },
    (error) => {
      console.error("Error getting location:", error.message);
    }
  );
} else {
  console.log("Geolocation is not supported by this browser.");
}

The position Object Explained

position.coords.latitude    // Latitude
position.coords.longitude   // Longitude
position.coords.accuracy    // Accuracy in meters
position.coords.altitude    // Altitude (if available)
position.coords.speed       // Speed (if available)
position.timestamp          // Time location was obtained

Example 2: Using Options for Better Control

const options = {
  enableHighAccuracy: true, // Uses GPS if available
  timeout: 5000,            // Wait max 5 seconds
  maximumAge: 0             // Do not use cached position
};

navigator.geolocation.getCurrentPosition(
  (position) => {
    console.log(position.coords);
  },
  (error) => {
    console.error(error.message);
  },
  options
);

Handling Errors Properly

function handleError(error) {
  switch (error.code) {
    case error.PERMISSION_DENIED:
      console.log("User denied the request for Geolocation.");
      break;
    case error.POSITION_UNAVAILABLE:
      console.log("Location information is unavailable.");
      break;
    case error.TIMEOUT:
      console.log("The request to get user location timed out.");
      break;
    default:
      console.log("An unknown error occurred.");
  }
}

Example 3: Watching User’s Location (Real-Time Tracking)

const watchId = navigator.geolocation.watchPosition(
  (position) => {
    console.log("Updated location:", position.coords);
  },
  (error) => {
    console.error(error.message);
  }
);

// Stop watching later
navigator.geolocation.clearWatch(watchId);

Use cases:

  • Fitness tracking
  • Delivery tracking
  • Navigation apps

Codeflare offers a 3-month intensive software development training in Abuja, designed to equip students with job-ready coding skills and practical experience that employers look for.

Common Real-World Use Case (Maps)

function openInGoogleMaps(lat, lng) {
  window.open(
    `https://www.google.com/maps?q=${lat},${lng}`,
    "_blank"
  );
}

Privacy & Best Practices

  • Always explain why you need the user’s location
  • Request location only when needed
  • Handle permission denial gracefully
  • Never store precise location without consent

Limitations

  • Not always precise (especially on desktops)
  • Requires internet & permissions
  • Can be blocked by browser or OS settings

Summary

The JavaScript Geolocation API lets you:
✔ Get the user’s current location
✔ Track movement in real time
✔ Build location-aware web apps

It’s simple to use, powerful, and must be handled responsibly.

Share
Published by
codeflare

Recent Posts

The Golden Ratio (φ)

1. What Is the Golden Ratio? The Golden Ratio, represented by the Greek letter φ (phi), is…

1 week ago

CSS Combinators

In CSS, combinators define relationships between selectors. Instead of selecting elements individually, combinators allow you to target elements based…

1 week ago

Boolean Algebra

Below is a comprehensive, beginner-friendly, yet deeply detailed guide to Boolean Algebra, complete with definitions, laws,…

2 weeks ago

Why It’s Difficult to Debug Other People’s Code (And what Can be Done About it)

Debugging your own code is hard enough — debugging someone else’s code is a whole…

2 weeks ago

Complete Git Commands

Git is a free, open-source distributed version control system created by Linus Torvalds.It helps developers: Learn how to…

2 weeks ago

Bubble Sort Algorithm

Bubble Sort is one of the simplest sorting algorithms in computer science. Although it’s not…

2 weeks ago