HTML Geolocation API

🌎 Introduction to the Geolocation API

The HTML5 Geolocation API allows web applications to access the geographical location of a user's device, with their permission. This enables features like location-based services, maps, and personalized content. πŸ—ΊοΈ

>>β€œKnowing where you are is the first step to getting anywhere.” πŸš€

βš™οΈ How Geolocation Works

The API uses various sources like GPS, Wi-Fi, IP address, or cell towers to determine the device’s location. It provides latitude, longitude, accuracy, and more.

πŸ“Œ Basic Geolocation Example

Getting User Location

if ("geolocation" in navigator) {
  navigator.geolocation.getCurrentPosition(
    (position) => {
      console.log("Latitude:", position.coords.latitude);
      console.log("Longitude:", position.coords.longitude);
      console.log("Accuracy (meters):", position.coords.accuracy);
    },
    (error) => {
      console.error("Error getting location:", error.message);
    }
  );
} else {
  console.log("Geolocation is not supported by this browser.");
}

Note

⚠️ Always ask for permission; users can deny access.

πŸ› οΈ Geolocation Methods

  • getCurrentPosition() – Gets current location once.
  • watchPosition() – Continuously tracks location updates.
  • clearWatch() – Stops the location tracking started by watchPosition().

πŸ”„ Watching Position Example

Tracking Location Changes

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

// To stop watching:
// navigator.geolocation.clearWatch(watchId);

🧠 Best Practices

  • Inform users why you need their location before requesting permission.
  • Handle errors gracefully (permission denied, timeout, unavailable).
  • Use watchPosition sparingly to save battery and resources.
  • Respect user privacy; do not share location data without consent.

πŸ”— Useful Resources

>>β€œLocation empowers context β€” build smarter, location-aware apps.” πŸ“²