Open In App

HTML Geolocation clearWatch() Method

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn the HTML geolocation clearWatch() method and its implementation. The clearWatch() method is used to cancel the currently running watchPosition() call and removes the location or errors generated as a result of the previous call.

Syntax:

navigator.geolocation.clearWatch(clearId);

Parameter:

  • clearId: The parameter ‘clearId’ is returned by the watchPosition() call itself. It is used to identify the watchPosition() call which we have to remove.

Example: The example below illustrate the geolocation clearWatch() method:

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
    <title>HTML Geolocation clearWatch() Method</title>
</head>
  
<body>
    <h2>Welcome To GFG</h2>
  
    <button onclick="getPosition()">
        Watch Position
    </button>
      
    <p id="demo"></p>
  
    <button onclick="clearPosition()">
        Clear Position
    </button>
  
    <script>
        var clearId;
        var demoPara = document.getElementById("demo");
        var user_loc = navigator.geolocation;
  
        function getPosition() {
            if (user_loc) {
                var option = { timeout: 50000 }
                clearId = user_loc.watchPosition(
                    currentLoc, resolveError, option);
            }
            else {
                "Your browser doesn't support Geolocation API.";
            }
        }
  
        function currentLoc(loc) {
            var lat = loc.coords.latitude;
            var long = loc.coords.longitude;
            demoPara.innerHTML = "Latitude: " 
                + lat + "<br>Longitude: " + long;
        }
  
        function resolveError(err) {
            demoPara.innerHTML = "ERROR" 
                + err.code + ": " + err.message;
        }
  
        function clearPosition() {
            demoPara.innerHTML = user_loc.clearWatch(clearId);
        }
    </script>
</body>
  
</html>


Output:

Explaining clearWatch() method

Supported Browsers:

  • Google Chrome 5.0
  • Microsoft Edge 12.0
  • Firefox 3.5
  • Internet Explorer 9.0
  • Safari 5.0
  • Opera 10.6


Last Updated : 14 Jan, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads