Using the Geolocation API



Location services depend on the Global Positioning System (GPS), IP addresses, and other device characteristics. You can take advantage of geolocation in web applications by leveraging browsers that support the Geolocation API.

You can get a reference to the Geolocation API from the window.navigator property, as follows:

var geoLocator = window.navigator.geolocation;

The code saves a reference to the Geolocation API in a variable to provide shorthand access to the API during future use.

The Geolocation API supports three key methods that you use to interact with it:

  1. getCurrentPosition
  2. watchPosition
  3. clearWatch

Using the getCurrentPosition method

You use getCurrentPosition to get exactly the current position of the user. This method takes one required parameter and two optional parameters.

  • The first parameter is a callback method that the API calls after the current position is determined.
  • The second parameter is optional, but it’s also a callback function called when an error occurs.

The code below gives an example of using the getCurrentPosition method:

getCurrentPosition(positionCallback, [positionErrorCallback], [positionOptions])

The last optional parameter is an object called PositionOptions, which lets you set some special options that control how the getCurrentPosition method behaves.

The following Table list the properties available on the PositionOptions object:

Property Description
enableHighAccuracy This causes the method to be more resource intensive if set to true. The default is false. If true, the getCurrentPosition method tries to get as close as it can to the actual location.
timeout This specifies a timeout period for how long the getCurrentPosition method can take to complete. This number is measured in milliseconds and defaults to zero. A value of zero represents infinite.
maximumAge If this is set, the API is being told to use a cached result if available, rather than make a new call to get the current position. The default is zero, so a new call is always be made. If maximumAge is set to a value and the cache isn’t older than the allowable age, the cached copy is used. This value is measured in milliseconds.

When the code runs in the browser, the users are asked whether they want to allow this application to determine their location.

The following code gives an complete example when using the getCurrentPosition method:

<body>
<div id="geoResults">
    <h1>Geolocation - Using the getCurrentPosition method</h1>
    <p>Current Location is:</p>
</div>
<script type="text/javascript">
    window.onload = function () {
        var geoLocator = window.navigator.geolocation;
        var posOptions = { enableHighAccuracy: true, timeout: 45000 };
        geoLocator.getCurrentPosition(successPosition, errorPosition,
        posOptions);
    }
    function successPosition(pos) {
        alert(pos);
    }
    function errorPosition(err) {
        alert(err);
    }
    function successPosition(pos) {
        var sp = document.createElement("p");
        sp.innerText = "Latitude: " + pos.coords.latitude +
        " Longitude: " + pos.coords.longitude;
        document.getElementById("geoResults").appendChild(sp);
    }
    function errorPosition(err) {
        var sp = document.createElement("p");
        sp.innerText = "error: " + err.message; + " code: " + err.code;
        document.getElementById("geoResults").appendChild(sp);
    }
</script>
</body>

The success callback method receives a position object, whereas the error method receives an error object. The position object exposes two properties:

  • The timestamp property indicates the time at which the coords were received.
  • The coords property is itself a coordinates object that contains the latitude, longitude, altitude, heading, and speed of the device’s current position and/or relative to the last position acquired.

The positionError object contains two properties: one for the code and one for the message.

Using the watchPosition method

The watchPosition method provides a built-in mechanism that continuously polls for the current position.

The watchPosition method takes the same set of parameters as the getCurrentPosition method but returns a watchPosition object.

The code below gives an example:

geoLocator.watchPosition(successCallBack,errorCallback,positionOptions)
           var watcher = geoLocator.watchPosition...

The watcher variable holds a reference to the watchPosition. The method calls the success callback method every time the Geolocation API detects a new location. The polling continues forever unless it you stop it.

You can cancel polling by calling the clearWatch method. The code below shows the full solution for the watchPosition method:

<body>
<div id="geoResults">
    <h1>Geolocation - Using the watchPosition method</h1>
    <p>Current Location is:</p>
</div>
<script type="text/javascript">
    window.onload = function () {
        var geoLocator = window.navigator.geolocation;
        var posOptions = { enableHighAccuracy: true, timeout: 45000 };
        geoLocator.getCurrentPosition(successPosition, errorPosition,
        posOptions);
    }
    function successPosition(pos) {
        alert(pos);
    }
    function errorPosition(err) {
        alert(err);
    }
</script>
<script type="text/javascript">
    var watcher;
    var geoLocator;
    window.onload = function () {
        geoLocator = window.navigator.geolocation;
        var posOptions = { enableHighAccuracy: true, timeout: 45000 };
        watcher = geoLocator.watchPosition(successPosition, errorPosition, posOptions);
    }
    function successPosition(pos) {
        var sp = document.createElement("p");
        sp.innerText = "Latitude: " + pos.coords.latitude + " Longitude: "
        + pos.coords.longitude;
        document.getElementById("geoResults").appendChild(sp);
        geoLocator.clearWatch(watcher);
    }
    function errorPosition(err) {
        var sp = document.createElement("p");
        sp.innerText = "error: " + err.message; + " code: " + err.code;
        document.getElementById("geoResults").appendChild(sp);
    }
</script>
</body>

Ads Right