dcsimg

Navigating HTML5 Geolocation

By Octavia Anghel

WEBINAR:
On-Demand

Desktop-as-a-Service Designed for Any Cloud ? Nutanix Frame


Since using GPS navigation is very common nowadays, it has completely changed the way people use maps. Everything is digitalized, and paper version of maps are now outdated. However, with the ability to know exactly where you are, you must agree that you allow the application to do so, because gathering your data without your permission endangers your privacy. That is why applications that use HTML Geolocation will always ask for your permission. So, the user will be prompted with a popup or dialog requesting the user's permission to share the location information. The user can accept or deny the request. The Geolocation API of HTML5 helps in identifying the user's location, which can be used to provide location-specific information or route navigation details to the user.

There are many techniques used to identify the location of the user. A desktop browser generally uses WIFI- or IP-based positioning techniques, whereas a mobile browser uses cell triangulation, GPS, A-GPS, WIFI-based positioning techniques, etc. The Geolocation API uses any one of these techniques to identify the user's location. At the base of every location-based application is positioning and Geolocation which is similar to the use of positioning systems but is more focused on determining a meaningful location (such as a street address) rather than just a set of geographic coordinates.

In this article, you will learn the Geolocation capabilities of HTML5. The API provides a method to locate the user's, more or less exact, position. This is useful in a number of ways that range from providing a user with location-specific information to providing route navigation. There is more than one way to figure out where you are — your IP address, your wireless network connection, which cell tower your phone is talking to, or dedicated GPS hardware that calculates latitude and longitude from information sent by satellites.

In HTML5, we have a set of APIs to effectively allow the client-side device (i.e. your iPhone 3G+, Android 2.0+ phones, or even your conventional desktop browsers) to retrieve geographic positioning information with JavaScript. The Geolocation API is supported by the following browsers and smartphones. Minimum version requirements are mentioned as well.

  • Google Chrome 5.0
  • Internet Explorer 9.0
  • Firefox 3.5
  • Safari 5.0
  • Opera 16.0
  • iPhone 3.0
  • Android 2.0
  • Opera Mobile 10
  • Blackberry OS 6.0

Locate the User's Position

The HTML Geolocation API is used to get the geographical position of a user. Since this can compromise privacy, the position is not available unless the user approves it.

To return the user's position, the getCurrentPosition() method is used.

The example below returns the latitude and longitude of the user's position:

<!DOCTYPE html>
<html>
<body>

<button onclick="getLocation()">Your coordinates are:</button>

<p id="Test"></p>

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

function getLocation() {
    //Check if Geolocation is supported 
    if (navigator.geolocation) {
	  //If supported, run the getCurrentPosition() method
	  //If the getCurrentPosition() method is successful, it returns a coordinates object to the function specified in the parameter (showPosition)
        navigator.geolocation.getCurrentPosition(showPosition);
    } else { 
	  //If not, display a message to the user
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

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

</body>
</html>

After pressing the button, you should get you own coordinates:

Handling Errors

The second parameter of the getCurrentPosition() method is used to manage errors. Possible error codes are:

  • when the user rejected the request
  • when the HTML5 geolocation information is unavailable
  • when the request for the location information has timed out
  • when the occurred error cannot be specified
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;
    }
}

The getCurrentPosition() Method - Return Data

The getCurrentPosition() method returns an object on success. Notice that the latitude, longitude and accuracy properties are always returned. The other properties are returned if available:

Periodic Updates of Geolocation Position

If you're building a cool web app or mobile app, you could use the watchPosition(); method instead of getCurrentPosition(), as this retrieves periodic updates about the current geographic location of the device. To clear anything being watched, simply use the clearWatch(); method when necessary:

  • watchPosition() — Returns the current position of the user and continues to return updated position as the user moves (like the GPS in a car).
  • clearWatch() — Stops the watchPosition() method.

The example below shows the watchPosition() method:

<!DOCTYPE html>
<html>
<body>

<button onclick="getLocation()">Your coordinates are:</button>

<p id="Test"></p>

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

function getLocation() {
    //Check if Geolocation is supported 
    if (navigator.geolocation) {
	  //the watchposition() method show the position of the user and update it while is moving
	    navigator.geolocation.watchPosition(showPosition);
    } else { 
	  //If not, display a message to the user
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
//The showPosition() function outputs the Latitude and Longitude
function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude;
}
</script>

</body>
</html>

Display the Result in a Map

The example below shows my position on the map, using the getCurrentPosition() method and places a square as a pushpin over it. To get a credential key map, you should have a Microsoft account that you will use to sign in here: https://www.bingmapsportal.com/. On the My account dropdown you will find the My keys option, where you can create your key.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script type='text/javascript'
            src='http://www.bing.com/api/maps/mapcontrol?callback=GetMap'
            async defer></script>
    <script type='text/javascript'>
    var map;
    var svgTemplate = '<svg xmlns="http://www.w3.org/2000/svg" width="84" height="25"><foreignObject width="100%" height="100%"><div        
    xmlns="http://www.w3.org/1999/xhtml">{htmlContent}</div></foreignObject></svg>';

    function GetMap() {
	map = new Microsoft.Maps.Map('#myMap', {credentials: 	'PLACE HERE YOUR KEY'});
                // Check if browser supports geolocation
                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(locateSuccess, locateFail);
                }
                else {
                    alert('I\'m sorry, but Geolocation is not supported in your current browser!');
                }

        var customHtml = '<div style="font-size:12px;border:solid 2px;background-color:lightgreen;padding:2px;">You found me!</div>';

        //Create custom Pushpin using an SVG string.
        var pin = new Microsoft.Maps.Pushpin(map.getCenter(), {
            icon: svgTemplate.replace('{htmlContent}', customHtml),
            anchor: new Microsoft.Maps.Point(25, 5)
        });

        //Add the pushpin to the map.
        map.entities.push(pin);
	}	
	// Successful geolocation
      function locateSuccess(loc) {
             // Set the user's location
             var userLocation = new Microsoft.Maps.Location(loc.coords.latitude,loc.coords.longitude);
             // Zoom in on user's location on map
             map.setView({ center: userLocation, zoom: 17 });
            }
      // Unsuccessful geolocation
      function locateFail(geoPositionError) {
            switch (geoPositionError.code) {
                 case 0: // UNKNOWN_ERROR
                     alert('An unknown error occurred, sorry');
                     break;
                 case 1: // PERMISSION_DENIED
                     alert('Permission to use Geolocation was denied');
                     break;
                 case 2: // POSITION_UNAVAILABLE
                     alert('Couldn\'t find you...');
                     break;
                 case 3: // TIMEOUT
                     alert('The Geolocation request took too long and timed out');
                     break;
                 default:
                }
            }
    </script>
</head>
<body>
    <div id="myMap" style="position:relative;width:600px;height:400px;"></div>
</body>
</html>

Conclusion

Hopefully, this article has shown you how to use HTML5 Geolocation to determine the location of a user.



Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
  •  
  •  
  •  
Thanks for your registration, follow us on our social networks to keep up-to-date