Geolocation clearWatch() API



The HTML Geolocation clearWatch() method is used to cancel an ongoing watchPosition call on our device. To apply the watchPosition call, we use watchPosition() method which automatically updates the location of devices whenever it changes.

When cancelled, the watchPosition call stops retrieving updates about the current geographic location of the device.

Syntax

Here is the syntax of HTML Geolocation clearWatch() method −

clearWatch(watchId);

Parameters

Here is the detail of parameter −

  • watchId − This specifies the unique ID of the watchPosition call to cancel. The ID is returned by the watchPosition call.

Return value

The HTML Geolocation clearWatch() method does not return a value.

Example

The code below demonstrates how to retrieve and cancel the geolocation information of user's device. The showLocation() method is defined to retrieve geolocation data and stopWatch() is for cancelling the watchPosition call.

<!DOCTYPE HTML>

<html>
   <head>
   
      <script type = "text/javascript">
         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);
         }
      </script>
   </head>
   
   <body>
      
      <form>
         <input type = "button" onclick = "getLocationUpdate();" value = "Watch Update"/>
         <input type = "button" onclick = "stopWatch();" value = "Stop Watch"/>
      </form>
      
   </body>
</html>

On executing, this code will produce two buttons. Clicking on the first one will ask for a geolocation update and clicking on the second one will stop the update.

html_geolocation.htm
Advertisements