JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Web Geolocation API


The Geolocation API allows web pages to get the geographic location of a user. With it, you can access latitude, longitude, altitude, and more. This API is widely used in maps, location-based services, weather apps, and delivery services.

What Is the Geolocation API?

The Geolocation API is a browser feature that lets JavaScript determine the user’s current position.

Key points:

  • Requires user permission to access location.

  • Works on most modern browsers.

  • Provides high-level accuracy if supported by GPS, Wi-Fi, or IP address.

  • Returns a position object with coordinates and additional data.

Accessing the Geolocation API

The Geolocation API is accessed through:

navigator.geolocation

It has two main methods:

Method Description
getCurrentPosition(success, error, options) Gets the current location once.
watchPosition(success, error, options) Continuously monitors the user’s location.

Getting Current Location

Example: Basic Location Fetch

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

Explanation:

  • getCurrentPosition gets the current coordinates.

  • position.coords.latitude and position.coords.longitude return the location.

  • error.message shows why location could not be obtained.

4. Handling Errors

The error callback receives an object with a code and message.

Code Meaning
1 Permission denied
2 Position unavailable
3 Timeout

Example: Error Handling

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

Using Options

You can pass an options object to getCurrentPosition or watchPosition to control accuracy and timeout.

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

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

Explanation:

  • enableHighAccuracy improves accuracy but may consume more battery.

  • timeout specifies maximum wait time.

  • maximumAge prevents using old cached location.

Watching Position

watchPosition continuously monitors location changes and calls the success callback whenever coordinates change.

Example: Track User Movement

if (navigator.geolocation) {
  const watchId = navigator.geolocation.watchPosition(
    function(position) {
      console.log("Updated Latitude:", position.coords.latitude);
      console.log("Updated Longitude:", position.coords.longitude);
    },
    function(error) {
      console.error("Error:", error.message);
    },
    { enableHighAccuracy: true }
  );

  // Stop watching after 30 seconds
  setTimeout(() => {
    navigator.geolocation.clearWatch(watchId);
    console.log("Stopped watching position.");
  }, 30000);
}

Explanation:

  • watchPosition tracks changes automatically.

  • clearWatch stops tracking using the returned watchId.

Displaying Location on a Map

You can integrate Geolocation with Google Maps or Leaflet.js to show the user’s location visually.

Example: Google Maps Integration

<div id="map" style="width: 500px; height: 300px;"></div>

<script>
function initMap(lat, lng) {
  const location = { lat: lat, lng: lng };
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 12,
    center: location
  });
  new google.maps.Marker({ position: location, map: map });
}

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
    initMap(position.coords.latitude, position.coords.longitude);
  });
}
</script>

<!-- Remember to include Google Maps API script -->

Explanation:

  • The user’s coordinates center the map.

  • A marker shows the exact location.

  • Requires a Google Maps API key.

Privacy and Security

  • Browsers require HTTPS for geolocation.

  • Users must grant permission.

  • Always inform users why you need their location.

  • Avoid storing precise coordinates unless necessary.

Real-World Applications

  1. Maps and navigation apps – show user location and routes.

  2. Weather apps – display weather for the current location.

  3. Delivery services – track delivery or pickup locations.

  4. Location-based content – customize content based on region.

  5. Fitness apps – track running or cycling paths.

Summary of the Tutorial

The Web Geolocation API allows you to access and use the user’s location safely and efficiently.

Key points:

  • Use navigator.geolocation.getCurrentPosition() for a single fetch.

  • Use watchPosition() to continuously track movement.

  • Always handle errors and ask for user permission.

  • Use options for accuracy, timeout, and cached positions.

  • Can integrate with maps or location-based services.

With this API, you can build dynamic, location-aware web applications that enhance user experience.


Practice Questions

  1. Write JavaScript code to get the user’s current latitude and longitude and display them in <p> elements.

  2. Create a function using getCurrentPosition that alerts the user’s coordinates when a button is clicked.

  3. Implement error handling to show a message if the user denies location access.

  4. Use watchPosition to log the user’s updated coordinates whenever they move, and stop watching after 20 seconds.

  5. Create a map using Google Maps API and center it on the user’s current location.

  6. Build a small app that fetches the user’s location and displays it in a formatted string: “Latitude: xx, Longitude: yy.”

  7. Use getCurrentPosition with enableHighAccuracy: true and timeout: 5000 to get a precise location.

  8. Write a script that shows an alert with a custom message if location information is unavailable.

  9. Create a tracker that counts how many times the user’s location has changed in 30 seconds using watchPosition.

  10. Build a weather app example that gets the user’s coordinates and fetches weather data from an API (e.g., OpenWeatherMap).


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top