Geo location is a HTML5 API which helps in identifying the geographical location of a Website/Application user.

The geographical location of a user can be identified by using many techniques like IP Positioning, GPS and Wi-Fi.
Usually a desktop browser use IP positioning or Wi-Fi to find the user’s location whereas a mobile browser uses GPS, A-GPS and Wi-Fi to identify a user’s location.

Geo location API must ask the user before locating and sending the user’s information to any website. Geo location API protects the user’s privacy by mandating that the user permission should be sought.

Geo-location API details

The Geo-Location API defines the user’s location in terms of position objects and coordinate objects.

A position object contains a timestamp feature which apprises the time at which the location data is retrieved whereas a coordinate object has the following properties listed below:

  • Latitude, longitude – Geographic coordinates specified in decimal degrees
  • Accuracy – Represents the Accuracy level of the longitude and latitude coordinates in meters. Lesser the number Bigger is the accuracy
  • Altitude – Height of the position in meters above the mean sea level.
  • AltitudeAccuracy – Represents how far off the altitude position could be from the actual attitude value obtained in meters. If the number is low it represents the accuracy is high.
  • Heading – Provides 360 degree heading information
  • Speed – Indicates current speed of the device in meters per second

The properties like Altitude, AltitudeAccuracy, Speed and Heading are optional. The properties like Longitude, Latitude and Accuracy are guaranteed to be shown.

Check for Browser compatibility

You can detect if the browser supports geo-location API or not by using the geo-location property of the global navigator object.

if (navigator.geolocation) {

      // Get the user's current position

} else {

      alert('Geolocation is not supported in your browser');

}

Get the user’s current location

To get the current location of a user, go to ‘getcurrentposition’ feature of the navigator.geolocation object. This feature works with three parameters:

if (navigator.geolocation)  {                                              

// Get the user's current position

navigator.geolocation.getCurrentPosition(showPosition, showError, optn);

} else {

       alert('Geolocation is not supported in your browser');

}
 

1. Success callback function:

If the user accepts the request & allows the browser to identify its location and share with the website then the success callback function will invoke with the obtained location information as position object & the function will be called as its input parameter.

function showPosition(position) {

        document.write('Latitude: '+position.coords.latitude+'Longitude: '+position.coords.longitude);

}

2. Error callback function:

If anything goes wrong and your browser could not identify user’s location then your error callback function will be called with a 'PositionError object' as its input parameter.

This is an optional callback function and invoked under any of these conditions:

  • Error occurred (unknown)
  • Request timed out
  • User has denied sharing its location.
  • Location information unavailable

function showError(error) {

     switch(error.code) {

          case error.PERMISSION_DENIED:

          alert("User denied the request for Geolocation.");

          break;

          case error.POSITION_UNAVAILABLE:

          alert("Location information is unavailable.");

          break;

          case error.TIMEOUT:

          alert("The request to get user location timed out.");

          break;

          case error.UNKNOWN_ERROR:

          alert("An unknown error occurred.");

          break;

    }

}

3. Position options:

These are the optional functions which can be use while retrieving the user’s location:

  • enableHighAccuracy: Boolean. If true & the device can support it, the user agent will try to identify the exact location of the user resulting in higher power consumption and slower response by your device. If false, the obtained position will be uncertain and less accurate. Default value is false.
  • Timeout: Positive long value. The timeout property is the number of milliseconds that the user agent takes to respond with the location information. Default value is Infinity.
  • maximumAge: Positive long value . The maximumAge attribute indicates that cached location data should be no older than the specified time in milliseconds. The Default value of this function is set to zero.

if (navigator.geolocation) {

      var optn = {

           enableHighAccuracy : true,

           timeout : Infinity,

           maximumAge : 0

      };

     navigator.geolocation.getCurrentPosition(showPosition, showError, optn);                 

} else {

     alert('Geolocation is not supported in your browser');

}

NOTE: Before running any Geo-Location API on your browser (including desktops) you will have to share the location with the browser. Here is how it's done in Chrome. Be aware that if it still doesn't work, you may need to clear the cookies and restart the browser. You can alway try the example on Firefox as well. If set to the default settings, it is going to run properly.

Example

Geo-location API Example (SAMPLE CODE)

Some Great uses of Geo-location

  • Online Cab Provider Companies uses Geo-Location API to provide their customer better service on location basis.
  • Used by E-Commerce websites to calculate shipping charges on the basis of customer’s location.
  • Real Estate Websites uses Geo-Location API to find out customer’s location to show better results nearby user.
  • Used by Movie theatre websites to find movies playing nearby user.
  • Online Gaming Websites.
  • Used by News Websites, Weather Forecast Websites, Job Providing Websites to serve the users on the basis of their location.