Labs ICT
Pro Login

Geolocation

Many modern web apps need to know where the user is — for maps, local weather, nearby restaurants, or location-based services. The Geolocation API lets you request the user's current location right from the browser. The user has to give permission, of course.

Getting the Current Position

You call navigator.geolocation.getCurrentPosition() and pass it a callback function. The browser asks the user for permission, and if they allow it, your callback receives a position object with latitude, longitude, and other details.


<script>
  function showPosition(position) {
    const lat = position.coords.latitude;
    const lon = position.coords.longitude;
    console.log(`Latitude: ${lat}, Longitude: ${lon}`);
  }

  navigator.geolocation.getCurrentPosition(showPosition);
</script>
    

Handling Errors

Geolocation can fail — the user might deny permission, the device might not have GPS, or the request might time out. Always provide an error callback to handle these situations gracefully.


<script>
  function showError(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('Request timed out');
        break;
    }
  }

  navigator.geolocation.getCurrentPosition(showPosition, showError);
</script>
    

Watching Position Changes

If the user is moving — like driving or walking — you can watch their position continuously. watchPosition() fires your callback every time the device detects a location change. It returns an ID you can use to stop watching later.


<script>
  const watchId = navigator.geolocation.watchPosition(
    (pos) => console.log(`Moved to: ${pos.coords.latitude}, ${pos.coords.longitude}`),
    showError
  );

  // Stop watching after 5 minutes
  setTimeout(() => navigator.geolocation.clearWatch(watchId), 300000);
</script>
    

Options for Accuracy

You can pass an options object to control the behavior. Set enableHighAccuracy to true for GPS-level precision (uses more battery). Set timeout to control how long to wait before giving up. Set maximumAge to accept a cached position instead of fetching fresh data.


<script>
  const options = {
    enableHighAccuracy: true,
    timeout: 10000,
    maximumAge: 60000
  };

  navigator.geolocation.getCurrentPosition(showPosition, showError, options);
</script>