Share via


Watching for Location Changes

A web application might request to continuously listen for location updates, for instance, to scroll a map each time the location changes. This topic provides a sample that uses the geolocation object's watchPosition method to receive location updates each time the position of the computer or device hosting the web application changes. To stop listening for updates, call clearWatch, passing it the return value of watchPosition.

In the following example, when the user clicks the Watch Latitude and Longitude button in the example, the example's listenForPositionUpdates function is called, which checks that the geolocation object is available before it calls watchPosition to start listening for location updates. When an update occurs, the success callback function updates the text boxes in the page by using the new latitude and longitude coordinates. The user clicks the Clear Watch button to stop listening for updates.

<!DOCTYPE html>    
<html>
<head>
<title>Geolocation API Example: Listening for Location Updates</title>
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<script type="text/javascript">

function setText(val, e) {
    document.getElementById(e).value = val;
}

var nav = null; 
var watchID;

function listenForPositionUpdates() {
  if (nav == null) {
      nav = window.navigator;
  }
  if (nav != null) {
      var geoloc = nav.geolocation;
      if (geoloc != null) {
          watchID = geoloc.watchPosition(successCallback);
      }
      else {
          alert("geolocation not supported");
      }
  }
  else {
      alert("Navigator not found");
  }
}


function clearWatch(watchID) {
    window.navigator.geolocation.clearWatch(watchID);
}


function successCallback(position)
{
   setText(position.coords.latitude, "latitude");
   setText(position.coords.longitude, "longitude");
}


</script>
</head>
<body>
<label for="latitude">Latitude: </label><input id="latitude" /> <br />
<label for="longitude">Longitude: </label><input id="longitude" /> <br />
<input type="button" value="Watch Latitude and Longitude" onclick="listenForPositionUpdates()" /> 
<input type="button" value="Clear watch" onclick="clearWatch()" />

</body>
</html>

Handling Errors

How to Create a Location-Aware Webpage

Getting the Current Location

Specifying the Time-out Duration