Cancels ongoing watchPosition call in HTML5

The clearWatch method cancels an ongoing watchPosition call. When canceled, the watchPosition call stops retrieving updates about the current geographic location of the device.

Syntax

navigator.geolocation.clearWatch(watchID);

Parameters

The clearWatch method takes one parameter:

  • watchID: The ID returned by watchPosition() that identifies the watch operation to cancel

Example: Watch and Stop Location Updates

<!DOCTYPE HTML>
<html>
   <head>
      <script>
         var watchID;
         var geoLoc;

         function showLocation(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            alert("Latitude : " + latitude + " Longitude: " + longitude);
         }

         function errorHandler(err) {
            if(err.code == 1) {
               alert("Error: Access is denied!");
            }
            else if( err.code == 2) {
               alert("Error: Position is unavailable!");
            }
         }

         function getLocationUpdate(){
            if(navigator.geolocation){
               // timeout at 60000 milliseconds (60 seconds)
               var options = {timeout:60000};
               geoLoc = navigator.geolocation;
               watchID = geoLoc.watchPosition(showLocation, errorHandler, options);
            }
            else{
               alert("Sorry, browser does not support geolocation!");
            }
         }

         function stopWatch(){
            geoLoc.clearWatch(watchID);
            alert("Location watching stopped!");
         }
      </script>
   </head>

   <body>
      <form>
         <input type="button" onclick="getLocationUpdate();" value="Watch Update"/>
         <input type="button" onclick="stopWatch();" value="Stop Watch"/>
      </form>
   </body>
</html>

How It Works

  1. Start watching: watchPosition() returns a unique watch ID
  2. Store ID: Save the watch ID in a variable for later use
  3. Cancel watching: Pass the watch ID to clearWatch() to stop location updates

Key Points

  • Always store the watch ID returned by watchPosition()
  • Calling clearWatch() immediately stops location monitoring
  • Good practice to clear watches when they're no longer needed to save battery
  • Multiple watches can run simultaneously with different IDs

Browser Compatibility

The clearWatch method is supported in all modern browsers that support the Geolocation API, including Chrome, Firefox, Safari, and Edge.

Conclusion

Use clearWatch() to stop location monitoring started by watchPosition(). Always store the watch ID and clear watches when no longer needed to optimize performance.

Updated on: 2026-03-15T23:18:59+05:30

323 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements