πŸ“ Geolocation API in JavaScript – Complete Tutorial

The Geolocation API allows web applications to access a user's geographic location (with the user's permission). It can provide latitude, longitude, altitude (if available), speed, heading, and accuracy information.

πŸ“Œ What is the Geolocation API?

The Geolocation API is a built-in browser API that retrieves the user's current location using GPS, Wi-Fi, mobile networks, or IP-based location services, depending on the device and browser capabilities.

>>"The Geolocation API provides location information only after the user grants permission."

πŸ’‘ Why Use the Geolocation API?

  • πŸ“ Find the user's current location
  • πŸ—ΊοΈ Display nearby places on a map
  • πŸš• Ride-sharing and delivery applications
  • 🌦️ Show local weather information
  • 🧭 Navigation and location-based services

πŸ›  Checking Browser Support

Before using the API, verify that the browser supports Geolocation.

Check Support

if ("geolocation" in navigator) {
  console.log("Geolocation is supported.");
} else {
  console.log("Geolocation is not supported.");
}

πŸ“ Getting the Current Location

Use getCurrentPosition() to retrieve the user's current location once.

Get Current Position

navigator.geolocation.getCurrentPosition(
  (position) => {
    console.log(position);
  }
);

πŸ“Š Accessing Location Data

The location information is available through theposition.coords object.

Read Coordinates

navigator.geolocation.getCurrentPosition(
  (position) => {
    console.log(position.coords.latitude);
    console.log(position.coords.longitude);
    console.log(position.coords.accuracy);
  }
);

πŸ“¦ Position Object

PropertyDescription
latitudeUser's latitude.
longitudeUser's longitude.
accuracyEstimated accuracy in meters.
altitudeHeight above sea level (if available).
altitudeAccuracyAccuracy of altitude.
headingDirection of travel in degrees.
speedSpeed in meters per second.

❌ Handling Errors

Provide an error callback to handle permission denials or other failures.

Error Callback

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

🚨 Error Codes

CodeDescription
1Permission denied.
2Position unavailable.
3Request timed out.

πŸ”„ Watching the User's Location

Use watchPosition() to receive location updates whenever the user's position changes.

Watch Position

const watchId =
  navigator.geolocation.watchPosition(
    (position) => {
      console.log(position.coords.latitude);
      console.log(position.coords.longitude);
    }
  );

πŸ›‘ Stop Watching

Stop receiving updates with clearWatch().

Clear Watch

navigator.geolocation.clearWatch(watchId);

βš™οΈ Geolocation Options

You can customize how location data is retrieved using an options object.

Options Example

const options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

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

πŸ“Š Options Explained

OptionDescription
enableHighAccuracyRequests more precise location (may use more battery).
timeoutMaximum time to wait before timing out.
maximumAgeMaximum acceptable age of a cached location.

πŸ›  Complete Example

HTML

<button id="btn">
Get Current Location
</button>

<p id="location"></p>

JavaScript

const btn =
  document.getElementById("btn");

const output =
  document.getElementById("location");

btn.addEventListener("click", () => {

  navigator.geolocation.getCurrentPosition(
    (position) => {
      output.textContent =
        `Latitude: ${position.coords.latitude},
Longitude: ${position.coords.longitude}`;
    },
    () => {
      output.textContent =
        "Unable to retrieve location.";
    }
  );

});

πŸ“Š getCurrentPosition() vs watchPosition()

FeaturegetCurrentPosition()watchPosition()
Returns Location Onceβœ… Yes❌ No
Continuous Updates❌ Noβœ… Yes
Best ForOne-time locationNavigation & tracking

⚠️ Important Notes

  • πŸ”’ The user must grant location permission.
  • 🌐 Most browsers require a secure context (HTTPS) to use the Geolocation API.
  • πŸ“± Accuracy depends on the device, signal quality, and available location providers.
  • πŸ”‹ High-accuracy mode may consume more battery.

Note

Always provide a fallback or helpful message when location access is denied or unavailable. Users should still be able to use your application whenever possible.

βœ… Best Practices

  • πŸ“ Request location only when it is actually needed.
  • ⚑ Use getCurrentPosition() for one-time lookups.
  • 🧭 Use watchPosition() only when continuous tracking is required.
  • ❌ Always handle errors and permission denials gracefully.
  • πŸ”‹ Disable location watching when it is no longer needed to conserve battery.

🎯 Summary

The Geolocation API enables web applications to access a user's location with permission. It provides methods like getCurrentPosition() for one-time location retrieval and watchPosition() for continuous tracking. It is commonly used in maps, navigation, weather, ride-sharing, and other location-aware applications.