HTML5 APIs – Geo Location


What is Geo-Location API ?

Geolocation API allows you to receive information on the user’s current geographical location.

Its introduced in HTML5, which identifies the latitude and longitude coordinates of the current website’s visitor.

Its then captured by javascript code and sent back to server, which shows the users current location on the website.

Before using Geolocation API we must have some prior knowledge in JavaScript.

Geolocation API is only available for HTTPS request.

Note: Our browser must support the geolocation to use it for the web application.

Why Geo-Location API is used ?

There are so many advantages upon using this API listed below,

1. Browser Context

        When we are searching in internet, our browser may want to query our location in order to provide locale-specific information that is relevant to your query.

        Example : Hotels located in our nearby area.

2. Weather Reports

        If we want to check the weather on our phone, the device will need Location set to ON in the phone’s Settings.

3. Social Media Updates


        Social media like Facebook/Twitter uses location APIs so users can tag their locations in their status updates.

        Example : show their friends where they are vacationing.

4. Employment and Business Networking

        Job searching websites use geolocation to match job searchers with opportunities available in their area.

5. Digital Maps

        Lost in a strange unknown city/place ? We can use our phone to pinpoint your location and find the fastest route to our destination place using Google Maps.

6. Marketing and Customer Engagement

        Web applications use a Geolocation API to monitor a user’s position when they’re out and about town.

7. Tracking IoT Devices

        Smart home devices or wearables, and vehicles can easily be tracked or located with geolocation.

8. Cybersecurity

        Geolocation can be used to track network intruders or suspicious system logins.

        Example : finding the crime location or hackers location etc.

Tutorial on html !!!

Click to Learn More about – HTML Tutorial for beginners

Geolocation violates the User privacy

By using Geolocation API, getting user’s location is the privacy concern or violation.

So geolocation API protects the user’s privacy by taking the user’s permission before getting the location.

This API notifies the user with option allow or deny, if the user allows then only his location will be identified.

What is Geolocation object ?

API property “navigator.geolocation” returns the Geolocation object as output.

This Geolocation object contains the user location informations.

“navigator.geolocation” checks the user permission for accessing their location.

If there is no user permission, it will ask the user for permission to access their location data.

And If they accept, then the browser will use the best available functionality on the webpage/device to access this information.

Syntax :

geo = navigator.geolocation

How to access the users location ?

Now we can access the user location information by using the below methods,

1. Geolocation.getCurrentPosition()

        Retrieves the device’s current location.

2. Geolocation.watchPosition()

        Calls the handler function automatically each time the position of the device changes, and returns the updated location.

3. clearWatch()

        This cancels the previous watchPosition() call.

What are the common arguments for Geolocation methods ?

Geolocation methods accepts three arguments, listed below

1. success callback

If the location retrieval is successful, the callback executes with a GeolocationPosition object as its only parameter, providing access to the location data.

2. error callback (optional)

If the location retrieval is unsuccessful, the callback executes with a GeolocationPositionError object as its only parameter, providing access information on what went wrong.

3. PositionOptions object(optional)

Defines various options for getting the location.

1. Geolocation.getCurrentPosition()

1. Success Callback(Checking the browser for user privacy)

Example :

<!DOCTYPE html>
<html>
<head>
    <title>Geolocation API</title>
</head>
<body>
  <h1>Geo Location for Finding Current Location</h1>
<button onclick="getlocation()">Check Browser Status</button>
<div id="location"></div>
<script>
    var x= document.getElementById("location");

    function getlocation() {
        if(navigator.geolocation){
            alert("Browser is supporting Geolocation API")
        }
        else
        {
            alert("Sorry! your browser is not supporting")
        }
    }
</script>
</body>
</html>

Output :

2. Position Object ( Getting the location object)

Example :

<!DOCTYPE html>
<html>
<body>

<p>Click to get Geo Location</p>

<button onclick="getLocation()">Get Location</button>

<p id="getLocation"></p>

<script>
var x = document.getElementById("getLocation");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude +
  "<br>Longitude: " + position.coords.longitude;
}
</script>

</body>
</html>

Output :

There are some more position properties available for Position object.

SnoPropertiesDescription

1

coords.latitude

Returns latitude of user location as a decimal number.

2

coords.longitude

Returns longitude of user location as a decimal number.

3

coords.altitude

Returns altitude in meters above the sea level (Only if available).

4

coords.accuracy

Returns the accuracy of the user’s position.

5

coords.altitudeAccuracy

Returns the altitude accuracy of user location. (If available)

6

coords.heading

Returns headings as degree clockwise from North. (If available)

7

coords.speed

Returns the speed in meter per seconds. (If available).

8

timestamp

Returns data or time of response. (If available).

Tutorial on html !!!

Click to Learn More about – HTML Tutorial for beginners

3. Error Callback( Error handled code )

Example :

<!DOCTYPE html>
<html>
<body>

<p>Click to get Geo Location</p>

<button onclick="getLocation()">Get Location</button>

<p id="getLocation"></p>

<script>
var x = document.getElementById("getLocation");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition,showError);
  } else {
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude +
  "<br>Longitude: " + position.coords.longitude;
}

function showError(error) {
  switch(error.code) {
    case error.PERMISSION_DENIED:
      x.innerHTML = "User denied the request for Geolocation."
      break;
    case error.POSITION_UNAVAILABLE:
      x.innerHTML = "Location information is unavailable."
      break;
    case error.TIMEOUT:
      x.innerHTML = "The request to get user location timed out."
      break;
    case error.UNKNOWN_ERROR:
      x.innerHTML = "An unknown error occurred."
      break;
  }
}

</script>

</body>
</html>

2. Geolocation.watchPosition()


When the user is moving from one location to other and the current accurate location of the changed position is retrieved using watchPosition() callback function.

watchPosition() function have all the parameters like getCurrentPosition() function.

Syntax

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

id – Defines the ID that can be used to uniquely identifying the user’s position.


This id is used in clearWatch() method to stop watching the user’s location.

3. clearWatch()

This cancels the previous watchPosition() call.

The id from watchPosition() call is passed to stop watching the users location.

Syntax :

navigator.geolocation.clearWatch(id);