Why geolocation is used?

HTML5 geolocation provides the possibility to display the location data/information for the user/ on the browser. Finding location by IP address of some location on the globe not always accurate, sometimes it is inaccurate and on other hand it is extremely hard to find.

The main discrepancy that we see by using the location by IP Address is the precision. IP addresses only provides a general idea of where someone might be(not accurate location, possible nearest location). However, Geolocation will provide us accurate information of where they are.

What is geolocation?

The Geolocation is new and one of the finest features of HTML5 API.

Geolocation is used to detect the client's geographic location for the web application.

Let’s learn about the geographic latitude and longitude numbers (coordinates) can be noticed by JavaScript and deliver the present location of our website's visitor to the server.

This feature is useful for giving well browsing knowledge about the site visitor.

For example, you can send the search results that are physically near to the client's location.

Now a day’s majority of the mobile devices and browsers supports the Geolocation API.

Nearly, all geolocation services uses the Network routing addresses like, RFID, WIFI, IP addresses, and international GPS device or MAC addresses to find the user's location.

Note! We totally understand the concept of Geolocation API we have some experience of JavaScript.

Advantages -

  • Geo-referencing - finding the relatively physical location of an object to the map.
  • Geo-coding - searching available objects types or services by location.
  • Geo-tagging - embedding geographic data into an object’s metadata for future reference.
  • Websites with the option of location base services, such as discovering places or people nearby, merged with mapping services.These all can help to generate a more satisfying experience with a service supplier and saves time.
  • If you are lost, you or others can know exactly where you are.
  • Can be used to find relevant local information such as - news and weather.
  • Helps in Connecting to social events.
  • Helps to find nearest stores and attractions and how far those from your location.
  • It allows several Companies advertising for their businesses. Also, by allowing the people do the marketing for them.
  • Monitoring and controlling workforce remotely.
  • Better control and following on-road transport.
  • Great event management through real time location alert and data.

Disadvantages -

  • Geolocation is a technology requires support or participation from the user.
  • Geolocation in most mobile devices take too much battery life and this makes users turn off the feature.
  • Geolocation is only limited to fixed radius and is good for large areas like a city.
  • It greatly Increases a person's exposure to identity theft.
  • Companies can overload applications with their advertisements. This slows down the internet and makes it a difficulty for users.
  • Informs the people about their current location which user don't want to know.
  • Anybody can harness geolocation information for any reason, fair or foul.

User privacy

The user's location is the privacy concern, so geolocation API maintains the user's privacy by obtaining the client's permission before fetching the client location.

Once the user provides permission, it obtains the location data of the user to website instead of directly obtaining.

API uses a dialog or popover for requesting the user’s approval to share the location data.

The user can deny or accept the request based on his interest.

Geolocation object

The geolocation object is a service object that allows widgets to get data about the geographic location.

The geolocation APIs works with a new property of the worldwide navigator object ie. Geolocation object can be created as follows −

var geolocation = navigator.geolocation;

Example -

Simple example for verifying browser supports Geolocation or not.
<!DOCTYPE html>
<html>
    <head>
        <title>Geolocation API</title>
    </head>
    <body>
        <h1>identify your present location</h1>
        <button onclick="getlocation()">Click me</button>
        <div id="location"></div>
        <script>
            var x= document.getElementById("location";
            function getlocation() {
                if(navigator.geolocation){ 
                    alert("your browser supports Geolocation API") 
                } 
                else 
                {  
                    alert("Sorry! Your browser do not supports 
                        Geolocation API") 
                }  
            }  
        </script>
    </body>
</html>                    

Output -

identify your present location

Geolocation Methods

The following table explains Geolocation API methods of Geolocation interface -

Methods Description
getCurrentPosition() This method recognizes the user's present location or device and returns a position object with information.
watchPosition() This method reclaims periodic updates about the present geographical position of the device
clearWatch() This method cancels the earlier watchPosition() call

Users current position

To find the users present location, we can use getcurrentPosition() method of the navigator.geolocation object.

This method allows 3 parameters such as success callback function, error callback function, position options.

  • Success callback - success callback function to obtain the location of the client.
  • Error callback function - error callback function will be used with the position error object as its input parameter.
  • Position options - position options define different options for finding the location.

Example -

The following example will return the latitude and longitude of the user’s present location.
<!DOCTYPE html>
<html>
    <head>
        <title>Geolocation API</title>
    </head>
    <body>
        <h1>identify your present position</h1>
        <button onclick="getlocation()">Click me</button>
        <div id="location"></div>
        <script>
            var x= document.getElementById("location");
            function getlocation() { 
                if(navigator.geolocation){  
                  navigator.geolocation.getCurrentPosition(showPosition)
                }  
                else   
                {   
                    alert("Sorry! your browser is not supporting") 
                } 
            } 
            function showPosition(position){ 
                var x = "Your current location is (" + "Latitude: " 
                + position.coords.latitude + "," +
                "Longitude:" +position.coords.longitude + ")";
                document.getElementById("location").innerHTML = x;
            } 
        </script>
    </body>
</html>   

Output -

identify your present position

Explaining Example (in Steps)-

  • initially testing the browser support
  • obtaining present position with getCurrentPosition()
  • obtaining longitude and latitude values with showPosition() method which is call back method of getCurrentPosition()

Geolocation Methods

In the getcurrentposition() the second parameter is an error callback function.

It is an optional parameter and used to manage the errors.It specifies a function to run If it collapses while getting the users location.

Following table defines the possible options for mentioning the error call back function -

Error code Meaning
error.PERMISSION_DENIED Request for location is timed-out
error.POSITION_UNAVAILABLE The HTML5 geolocation information is not available.
error.TIMEOUT If the user has rejected for sharing location.
error.UNKNOWN_ERROR Unknown random error Occurred

Example -

//..
navigator.geolocation.getCurrentPosition(callback, errorHandler);
//..
function errorHandler(error) {
    switch(error.code) { 
      case error.PERMISSION_DENIED:
        alert("Client rejected the request for Geolocation.");
        break;
      case error.POSITION_UNAVAILABLE:
        alert("the html5 geolocation information is  not available.");
        break;
      case error.TIMEOUT:
        alert(" request for location timed out.");
        break; 
      case error.UNKNOWN_ERROR:
        alert("unknown  random error occurred.");
        break;
    }
}   

Displaying location on a google map

Using latitude and longitude values, we have seen how to show your location in the earlier chapters, but it is not enough. Hence, we can also display the correct location on google map with this API.

Example -

Below example showing the exact location using google map.
(function() { 
    if(!!navigator.geolocation) { 
        var map;
        var mapOptions = {
            zoom: 14,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }; 
        map = new google.maps.Map(document.getElementById
                      ('google_canvas'), mapOptions);
        navigator.geolocation.getCurrentPosition(function(position) { 
        var geolocate = new google.maps.LatLng
            (position.coords.latitude, position.coords.longitude);
        var infowindow = new google.maps.InfoWindow({
            map: map, 
            position: geolocate,
            content: 
                '<h1>Location attached from HTML5 Geolocation!</h1>' +
                '<h2>Latitude: ' + position.coords.latitude + '</h2>' + 
                '<h2>Longitude: ' + position.coords.longitude + '</h2>'
            });
            map.setCenter(geolocate);
        });
   } else {
        document.getElementById('google_canvas')
           .innerHTML = 'No Geolocation Support.';
   }  
})();   

Location properties

Geolocation methods getPositionUsingMethodName() and getcurrentPosition() indicate the callback method that retrieves the user location information.

These methods are called asynchronously with an object Position which saves the entire location information.

The Position object stipulates the present geographic location of the mechanism.

The location is conveyed as a set of geographic coordinates (latitude and longitude numbers) together with information about speed and heading.

The following table explains the properties of the Position object -

Properties Description
coords.latitude It specifies latitude of client location as a decimal degree. The range of the value is [-90.00, +90.00].
coords.longitude It specifies longitude of client location as a decimal degree. The range of the value is [-180.00, +180.00].
coords.altitude It specifies altitude in meters above the WGS 84 ellipsoid.
coords.accuracy It returns the accuracy of latitude and longitude estimates in the meter
coords.altitudeAccuracy It specifies the altitude exactness of user location. (If available)
coords.heading It specifies headings as degree counting clockwise relative from North. (If available)
coords.speed It defines the speed in meter per seconds. (If available).
timestamp It returns time of response or data. (If available).

If the system cannot give a value for the optional properties, the property value is set to null.

Watching the current location

If we need to see the client location while he is moving and want exact location at every switching position, then it can be attained by using watchPosition() callback function.

This function has all three parameters which contains getCurrentPosition().

Syntax -

var id = navigator.geolocation.watchPosition(success[, error[, options]])

The watchPosition() method specifies an ID that can be used to individually finding the users location and we can also use this ID with clearWatch() method to stop seeing the location.

Syntax -

navigator.geolocation.clearWatch(id);
Position Options

exact syntax of getCurrentPosition() method as follows

getCurrentPosition(callback, ErrorCallback, options)

In the getcurrentPosition the third argument is the PositionOptions object which stipulates a set of options for reclaiming the geographic location of the device.

Given below are the options which can be stipulated as third argument −

Property Type Description
enableHighAccuracy Boolean returns whether the widget choose to obtain the most exact location estimate possible. By default, this is false.
timeout Number This property specifies number of milliseconds your web application is prepared to wait for a position.
maximumAge Number Specifies the end time in maximumAge Number milliseconds for hidden location information.

Browser support

The following table used to identify the initial browser version that completely supports Geolocation.

API Chrome Edge Firefox Safari Opera
Geolocation 5.0 49.0 (http) 50.0 (https) 9.0 3.5 3.5 16.0

The browser support for the Geolocation API helps the geolocation property of navigator.geolcation.