Conversation

Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!

Join the discussion and share your insights now!

Comments 0

Sharpen your coding skills—try JavaScript challenges on TOOLX now!

advertisement

A Beginner's Guide to Geolocation in HTML5

geolocation in html5


Introduction

Consider a scenario where you are visiting a new city unaware of specific locations and routes. You want to get information regarding hotels in your locality, such as their exact address, tariffs, and soon. In such a situation, an application that can provide relevant information about hotels based on your current location would be useful.

A feature that can detect location and list relevant information based on that location is called geolocation. Geolocation is a term used to identify the geographical location of a person, place, or object.

Today, modern devices, such as computers, smartphones, tablets, and so on provide Internet-enabled browsers through which the geographical location of a user or an object can be detected.


Geolocation

Geolocation in computing terminology indicates a feature that determines a user's current location on devices. The user's location is represented as a single point comprising two components: latitude and longitude. The components can be used further to retrieve more information for the user, such as businesses in the neighborhood or other users within the same coverage area.

There are different sources through which devices can determine location information. These are as follows:

  1. GPS - GPS is a satellite navigation system that provides information about the location of any part of the globe. GPS is maintained by the government of the United States and is used by modern mobile devices with GPS capability.

  2. IP Address - Location information can be derived from an IP address. The IP address is assigned to devices, such as desktops, printers, and so on connected to a network.

  3. GSM/CDMA Cell IDs - These are used by cell phones.

  4. WiFi and Bluetooth MAC addresses - These are used by devices that have wireless network connections.

  5. User Input - It is a software tool that can be used on any device to request location information. The information retrieved by the tool is based on the data provided by the user, such as a zip code.




Geolocation API

In HTML5, the Geolocation API is a specification provided by the W3C. It provides a consistent way to develop location-aware Web applications.

The Geolocation API provides a high-level interface that can be used by developers to retrieve location information related to hosting devices. The interface hides the details, such as how the information was gathered or which methods were used to retrieve the information. This helps the developer concentrate on geographical information rather than its processing methods.

The object that holds the implementation of the Geolocation API is the Geolocation object. This object is used in JavaScript to retrieve geographical information about devices programmatically. The browser processes the script and returns the location to the Geolocation AP.

The Geolocation API is supported on most of the modern browsers available on desktops and mobile phones.

Lists the browsers providing support for the Geolocation API.

  • Safari - 5.0+
  • Chrome - 5.0+
  • Firefox - 3.5+
  • Internet Explorer - 9.0+
  • Opera - 10.6+
  • iOS(Mobile Safari) - 3.2+
  • Android - 2.0+



Note - Information retrieved by the Geolocation App doesn't need to be the actual location of the device. For example, if the satellites are invisible to GPS, then they may not return accurate location information.




1. Implementing a Geolocation Object

The Geolocation object is available as a new property of the navigator object. The navigator object is a browser object that allows a user to retrieve information about a specific location.

The syntax shows how to create a geolocation object in JavaScript.

Syntax:

var geolocation = window.navigator.geolocation;

where,

window: Is the top-level object in the JavaScript object hierarchy

The script tests the existence of a Geolocation object within a browser.

<!DOCTYPE html>
<html>
<head>
    <title>Testing Support for Geolocation in Browsers</title>
    <script>
      function display() {
        // Default message
        var str = "Geolocation is not supported in this browser";
        if (window.navigator.geolocation) {
          str = "Geolocation is supported in this browser";
        }
          alert(str);
      }
    </script>
</head>
<body>
    <input type="button" value="Geolocation Support" onClick="display()">
</body>
</html>

In the code, the if statement checks the existence of the geolocation property in the browser. If the browser provides an implementation of the property, then an alert window displays the message 'Geolocation is supported in this browser'. Otherwise, the default message is displayed.


2. Geolocation methods

The Geolocation object provides three methods that can be used to determine the current position of the user.

Lists the methods of the Geolocation object.

  • getCurrentPosition(): Retrieves the current geographical location information of the user
  • watchPosition(): Retrieves geographical information of the device at regular intervals
  • ClearWatch(): Terminates the current watch process


Also, any changes in the user's position are notified through these methods.



3. Retrieve User Position

The current position of a user is retrieved using the getCurrentPosition (successCallback, errorCallback, options) method. This function accepts three parameters, of which two are optional, errorCallback, and options.

The first parameter, successCallback is the name of the function that is invoked after the position of a device is found successfully. The second parameter, errorCallback is the name of the function which will be called if an error occurs in retrieving the position. The last parameter, options represents a PositionOptions object.

The markup will retrieve the current location of the user.

<!DOCTYPE html>
<html>
<head>
<title>Geolocation API</title>
<script>
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        alert("Geolocation is not supported in this browser.");
    }
}
function showPosition(position) {
    alert('Latitude: ' + position.coords.latitude + '\nLongitude: ' + position.coords.longitude);
}
</script>
</head>
<body>
<input type="button" value="Display Location" onClick="getLocation()"/>
</body>
</html>

In the code, the getCurrentPosition () function obtains the position which is passed as a parameter to the showPosition () function. The showPosition () function obtains the coordinates of a location through the position object.

The position object is defined in the Geolocation API and holds the current location of the device. It contains an attribute named coords that retrieves the latitude and longitude of the location. The values retrieved for latitude and longitude are in decimal degrees.

Lists the attributes of the position object.

  • coords: An object of type Coordinates that provides different properties, such as latitude, longitude, altitude, accuracy, speed, and so on
  • timestamp: An object of type DOMTimeStamp


Note: The geolocation code works best in the Opera browser.



4. Handling errors

An application could fail at gathering geographical location information. In that case, the Geolocation object calls the errorCallback () function. The errorCallback () function handles errors by obtaining a PositionError object from the API.


PositionError Object
The PositionError object holds information related to errors that occurred while finding the geographical location of the user.

Lists the properties of the PositionError object

  • Code: Returns a numeric value for the type of error that occurred.
  • Message: Returns a detailed message describing the error encountered. The message can be used for debugging.


Lists different error codes returned by the code property of the PositionError object.

  • PERMISSION_DENIED: The application does not have permission to access the Geolocation API
  • POSITION_UNAVAILABLE: The position of the device could not be obtained
  • TIMEOUT: Unable to retrieve location information within the specified interval


The error-handling routine for the geolocation code.

<!DOCTYPE html>
<html>
<head>
    <title>Handling Error</title>
    <script>
        function getLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(showPosition, errorHandler);
            } else {
                alert("Geolocation is not supported in this browser.");
            }
        }
        function showPosition(position) {
            alert('Latitude: ' + position.coords.latitude + '\nLongitude: ' + position.coords.longitude);
        }
        function errorHandler(error) {
            switch (error.code) {
                case error.PERMISSION_DENIED:
                    alert("You have denied access to your position.");
                    break;
                case error.POSITION_UNAVAILABLE:
                    alert("There was a problem getting your position.");
                    break;
                case error.TIMEOUT:
                    alert("The application has timed out attempting to get your position.");
                    break;
                case error.UNKNOWN_ERROR:
                    alert("An unknown error occurred.");
                    break;
            }
        }
    </script>
</head>
<body>
    <input type="button" value="Display Location" onClick="getLocation()"/>
</body>
</html>

In the code, if the application fails to find the current location of the user, then the errorHandler () function is invoked. The function is passed as the second parameter in the getCurrentPosition () method and is used to handle errors that occur in the application. It obtains the error object which is of type PositionError from the API and compares it with the error codes specified in the switch-case statement. Depending on the error that has occurred, the appropriate case statement is executed and an alert message is displayed to the user.


5. PositionOptions Object

PositionOptions object is an optional third parameter passed to the getCurrentPosition() method. This object defines properties that are optional and are used by an application while retrieving geolocation information.

Lists the attributes of the PositionOptions object.

  • enableHighACcuracy: Indicates that the application wants to receive the most accurate results for geolocation. The default value of the attribute is false

  • maximumAge: Obtains the cached position object whose age is less than the specified maximumAge limit (in milliseconds). If the age limit is set to 0, then the application must obtain a new position object

  • timeout: Which indicates the maximum time length (in milliseconds) for which the application can wait to obtain the position object

The script sets the attributes of the Positionoptions object. This code replaces the relevant code.

<script>
   var options = {
      enableHighAccuracy: true,
      maximumAge: 50000,
      timeout: 60000
   };
   function getLocation() {
      if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition, errorHandler, options);
      } else {
      alert("Geolocation is not supported in this browser.");
      }
   }
</script>

In this code, an object named options is set with attributes. The attribute maximumAge enables the application to use a cached position object which is not older than 50 seconds. Also, the timeout limit is set to 60 seconds for an application, before notifying an error.

The options are passed as a third parameter to the getCurrentPosition() method.


HTML5 HTML Geolocation GPS Geolocation in HTML5 Geolocation API Implementing a Geolocation Object geolocation api example html geolocation google maps geolocation api javascript

advertisement