Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

HTML5 Geolocation implementation

In this article we will introduce how we can incorporate geolocation in our website with the help of HTML5.

Introduction:

You are visiting a city for the first time and looking for sight-seeing locations close to your hotel. However, you do not know where to go and which places to look for. Therefore, it will be helpful if you have some application that can help you locate such places and provide feedback for the same. This can be done by implementing Geolocation API.

Implementing Geolocation

ShopHere is a large retail store based in Ohio. The store offers clothes, accessories, and footwear. In addition, it sells the home furnishing goods and electronic items, such as refrigerator, air conditioner, laptops, and mobile devices. As part of its business strategy to attract new customers and build a stable customer base, the store offers discounts and special deals on products. In addition, the official website of the store has a feature that enables users to share their current location, based on which, they are guided to reach the nearest store. Such a feature is incorporated in websites by using the Geolocation API. The Geolocation API-enabled website can locate users’ current geographical location, display points of interest around that location, or guide the users from their current location to a target destination.

Implementing the Geolocation API

The Geolocation API allows a website to retrieve the current geographical location of a user. This API enables you to create applications that guide users how to reach a target location from their current location. An example of such an application is a map application that gives directions to a target location. The users’ location is not retrieved just through code or browser. Instead, the Geolocation API uses certain features, such as Global Positioning System (GPS), Internet Protocol (IP) address of a device, nearest mobile phone towers, and input from a user, in the users’ device to retrieve the users’ location. The users’ location retrieved by using the Geolocation API is almost accurate depending upon the type of source used to retrieve the location. For example, the IP address gives a location that can be close to the users’ location; while, the GPS is able to give more accurate results. Identifying the users’ location may, at times, compromise the users’ privacy. Hence, the location of users is not available unless they approve it. A prompt appears that asks the users if they would like to share their current location and also specifies the reason for collecting this data. In addition, it should specify where the data will be shared. Geolocation is most beneficial with applications used for mobile devices. This is because while the users are travelling, the Geolocation API keeps updating their locations. In case of desktop applications, the users’ location remains constant and can be set only once. The Geolocation API provides the following methods to determine the users’ location:

  • getCurrentPosition()
  • watchPosition()

getCurrentPosition()

The getCurrentPosition()method is used to retrieve the current geographical location of a user. The location is retrieved as a set of coordinates. The syntax of the getCurrentPosition() method is: getCurrentPosition(CallbackFunction, ErrorHandler, Options);

In the preceding syntax:

  • CallbackFunction: This is a function defined by the developer to retrieve the current location.
  • ErrorHandler: This is the name of a function that is called when an error occurs while retrieving the location of a user. This is an optional parameter.
  • Options: This optional parameter specifies a set of options, such as timeout for retrieving the location information, used for retrieving the information about the users’ geographical location.

The getCurrentPosition() method calls callbackFunction, which takes the positionobject as an argument. This object specifies the current geographic location of a user as a set of geographic coordinates. The positionobject returns two properties, coordsand timestamp, on the successful retrieval of the location. The timestampproperty returns the date and time when the location was retrieved. The coords property returns various attributes, such as latitudeand longitude.

Before retrieving the users’ location by using the getCurrentPosition() method, you need to check whether the browser supports the geolocation feature. For this, you can use the geolocationproperty of the navigatorobject. The navigatorobject contains the information about a browser.

Listing 1: Consider the following code snippet to check whether the browser supports the geolocation feature:

if(navigator.geolocation){
var geo=navigator.geolocation 
}else {
 alert("Your browser does not support geolocation") 
}

The preceding code snippet checks whether the geolocation feature is supported by the browser. If it is not supported, a relevant message is displayed.

Listing 2: Consider the following code snippet for retrieving the users’ location by using the getCurrentPosition() method:


<!DOCTYPE HTML> 
<HTML>
 <BODY>
 <P ID="button">Click here to know your location coordinates:</P>
 <BUTTON onclick="getLocation()">Get Location</Button>
 <SCRIPT>
 var geo=document.getElementById ("button");
 function getLocation() {
   if (navigator.geolocation) {
              navigator.geolocation.getCurrentPositi on(getPosition);
   } Else{geo.innerHTML="Geolocation is not supported by this browser.";} } 
    function getPosition(position) { 
        geo.innerHTML="Latitude: " + position.coords.latitude + "<BR>Longitude: " + position.coords.longitude; 
}
 </SCRIPT> 
</BODY>
 </HTML>

The preceding code snippet creates the Get Locationbutton, which, on clicking, calls the getLocation() method. This method first checks whether the geolocation feature is supported by the browser.

If this feature is supported, the getCurrentPosition() method is called. This method calls the getPosition() method that retrieves the users’ location in the form of latitude and longitude values.

watchPosition()

The watchPosition() method returns the current location of a user and continuously updates the location while the user is moving. It is mostly used in devices, such as GPS, which inform the users about the current location while they are travelling. The watchPosition() method takes the same parameters as the getCurrentPosition() method and returns the same object.

Listing 3: Consider the following code snippet for retrieving the users’ location by using the watchPosition() method:

function getLocation() {
if (navigator.geolocation){
   navigator.geolocation.watchPositio n(getPosition); 
}else{
   geo.innerHTML="Geolocation is not supported by this browser.";
}
} function getPosition(position) {
    geo.innerHTML="Latitude: " + position.coords.latitude + "<br>Longitude: " +position.coords.longitude;
 } 

The preceding code snippet continuously retrieves the user’s location by using the watchPosition() method while the user is travelling. You can also stop tracking the users’ location by using the clearWatch() method. This method stops the call to the watchPosition() method.

Handling Errors

At times, the user may not provide the permission to access his location. This may raise an error in your website. The error may also occur when a user checks the current location on a mobile device and the device goes out of coverage area or the network connection is timed out. As a website developer, you need to ensure that your website is able to handle errors effectively. For this, you need to consider all possible causes of errors that can occur in an application and can be dealt with effective error-handling technique.To handle errors in a geolocation-enabled website, you can use the getCurrentPosition()method. The second parameter of this method is an error handler function. This function can handle the following error codes:

  • PERMISSION_DENIED: Specifies that the user has declined the request to share the location.
  • POSITION_UNAVAILABLE: Specifies that the users’ current location cannot be retrieved.
  • TIMEOUT: Specifies that the time given to retrieve the users’ location has exceeded the maximum limit.
  • UNKNOWN_ERROR: Specifies that an unknown or undefined error has occurred.

The error handler function accepts the PositionError object as an argument. This object has two properties, code and message. The code specifies the error code, and the message specifies the message that is to be displayed when an error occurs.

Listing 4: Consider the following code snippet for handling errors while retrieving the users’ location:

function showError(PositionError) {
 switch(PositionError.code) {
  case PositionError.PERMISSION_DENIED: x.innerHTML="User denied the request for tracking the location" break;
  case PositionError.POSITION_UNAVAILABLE: x.innerHTML="User's location is not available" break;
  case PositionError.TIMEOUT:x.innerHTML="The request to retrieve user's location is timed out" break;
  case PositionError.UNKNOWN_ERROR:x.innerHTML="An unknown error occurred" break;
}
}

The preceding code snippet creates the function, showError(), which is called when an error occurs while retrieving the users’ location. This function accepts an error code which is defined in the switchconstruct. For example, if the user denies the access to his location, the error, User denied the request for tracking the location, is displayed on a Web page.

Conclusion

In the all above concepts there are lot of things were discussed regarding geoLocation and errors of it, this can be used for the general webpages as well as Mobile app development with HTML 5.



Have good knowledge on Java, HTML, CSS and Android platform and is pursuing Masters in Computer Applications.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login