Marcos Vainer Loeff

Geolocation in HTML5

Blog Post created by Marcos Vainer Loeff Employee on Aug 8, 2013


 

In this blog post, I will first introduce you to what Geolocation API is and how it could be used to find your current position which is returned with a given accuracy depending on the best location information source available. It will be shown how to create a HTML5 web page that shows you your latitude and longitude as well as its accuracy. On the next blog post, I will show you the mapping technology to add the ability to display your location in a map.

 


What is Geolocation API?

 The Geolocation API is an effort by the World Wide Web Consortium (W3C) to standardize an interface to retrieve the geographical location information for a client-side device.

 

It is ideally suited to web applications for mobile devices such as personal digital assistants (PDA) and smartphones. However, because of the wide variety of devices and mobile browsers, which usually lack plugin architecture, there is not yet widespread support on such platforms. On desktop computers, the W3C Geolocation API works in Firefox since version 3.5, Google Chrome, Opera 10.6, Internet Explorer 9.0, and Safari 5. On mobile devices, it works on Android (firmware 2.0 +), iOS, Windows Phone.

 

The technology that determines the location, however, varies greatly depending on the device capabilities and the client’s environment.

 


Geolocation Technologies

There are at least 10 different systems in use or being developed that a device could use to identify its location. In most cases, several are used in combination, with one stepping in where another becomes less effective. You can find the 10 different systems in this link. Below you can find information about the four most important ones.

 


GPS

Using GPS satellites to track location allows for maximum accuracy and specificity, especially in a low, flat area. In rural areas the geolocation accuracy by a technology using GPS is nearly 100%. However, if you are trying to track people who live in cities, the "valleys" of the urban landscape and the tall buildings often throw off GPS sensors. Additionally, GPS satellites typically take a long time to "fix" a user's location, and if a user is indoors, the whole system might not work properly.

 


Wi-Fi Positioning

In any given location, there may be dozens of Wi-Fi routers or providers. Wi-Fi positioning triangulates your position based on how many Wi-Fi networks are in range of your computer. Skyhook Wireless maintains a comprehensive database of wireless access points, and this database allows for highly accurate location gathering, particularly in urban environments which may hold thousands or even millions of wireless networks. It takes a short time to fix a user's location, and all it requires is a single software installation - ideally part of a web browser package - since most computers and mobile devices come with wireless radio. The only problem is that in rural areas, Wi-Fi positioning isn't very useful due to the relative lack of wireless networks.

 


IP Geolocation

IP Geolocation is easily implemented into a website, but it suffers from limitations of specificity. Each IP block corresponds roughly to a geographical area, so you can usually figure out what city someone is in. However, it often produces false positives, and the data should be checked against other forms of geolocation.

 


Cell Tower Triangulation

A lot like Wi-Fi positioning but on a larger scale, cell tower triangulation figures out where a user is based on the cellular signals the user is getting from towers. This is mostly useful for mobile devices which have built-in cellular radios, and serves to fill in any gaps from the above three sources of geolocation information. 

 

 

Creating a simple HTML5 page showing your geolocation information

When developing web applications, one option is to write code in a text editor, compile code at the command line, write HTML and CSS in a separate application, and manage your database on another one. However, a better option would be using Visual Studio which enable you to perform all of these tasks, and more, from the same environment.

 

Let’s start creating a web project using Visual Studio 2012 and the downloaded template “Pure HTML Web Site”. You can find more information about this template in my previous blog post “HTML5 in Visual Studio 2012”.  

 

Choose a name and a location for your solution and click OK.

 

 

 

2021.fig1.png

 

 

 

 

 

On the solution explorer, double click on the index.html file to view its content. Replace its content with the code shown below:

 

  

 
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Your current position page</title>
</head>
<body>
    <div style = 'width:800px; height:50px;'>
    <p>Information using the getCurrentPosition method:</p><br />
    <span id = 'gCP'> </span>
        <br />
    <p>Information using the watchPosition method:</p><br />
    <span id = 'wP'> </span>
    </div>
    <script type = 'text/javascript'>
        var gCP = document.getElementById('gCP');
        var wP = document.getElementById('wP');

        if (navigator.geolocation) { 
            navigator.geolocation.getCurrentPosition(showLocation,
            errorHandler,
            {
                maximumAge: 100,
                timeout: 6000,
                enableHighAccuracy: true
            });

            var l = navigator.geolocation.watchPosition(showMovingLocation,
            errorHandler,
            {
                maximumAge: 100,
                timeout: 6000,
                enableHighAccuracy: true
            });

        }
        else {
            alert('Geolocation not suported');
        }
        function showLocation(pos) {
            gCP.innerHTML =
            'Your latitude: ' + pos.coords.latitude +
            ' and longitude: ' + pos.coords.longitude +
            ' and timestamp ' + pos.timestamp +
            ' (Accuracy of: ' + pos.coords.accuracy + ' meters)';
        }

        function showMovingLocation(pos) {
            wP.innerHTML =
            'Your latitude: ' + pos.coords.latitude +
            ',longitude: ' + pos.coords.longitude + 
            ',speed: ' + pos.coords.speed +
            ',altitude: ' + pos.coords.altitude +
            ' and timestamp ' + pos.timestamp +
            ' (Accuracy of: ' + pos.coords.accuracy + ' meters)';
        }

        function errorHandler(e) {
            if (e.code === 1) { // PERMISSION_DENIED
                lbl.innerHTML = 'Permission denied. - ' + e.message;
            } else if (e.code === 2) { //POSITION_UNAVAILABLE
                lbl.innerHTML = 'Make sure your network connection is active and ' +
                'try this again. - ' + e.message;
            } else if (e.code === 3) { //TIMEOUT
                lbl.innerHTML = 'A timeout ocurred; try again. - ' + e.message;
            }
        }
</script>
</body>
</html>

 

 

 Press F5 to debug your application. Internet Explorer should open showing a similar page to the screenshot below:

 

 

 

 8233.fig2.jpg

 

 

 

 

 

The latitude and longitude shown above is from the center of the city of São Paulo, Brazil.

 


Explaining geolocation objects

As it was mentioned, there are common sources of location information that Geolocation API has access which include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs, as well as user input. Nevertheless, there is no guarantee that the API will return the correct location of the device.

 

The Geolocation API is provided by the geolocation object which is accessed through the navigator object.

 

To begin, the JavaScript code needs to check if Geolocation is supported by the browser. If this is false, a message is displayed to the user. If supported, it runs the getCurrentPosition() and watchPosition() methods.

 

 If the getCurrentPosition() method is successful, it returns a coordinates object to the function specified in the parameter (showLocation).

 

The latitude, longitude and accuracy properties are always returned. The other properties below are returned if available. Below there is a description about those properties:

  • The latitude and longitude attributes are geographic coordinates specified in decimal degrees.
     
  • The altitude attribute denotes the height of the position, specified in meters above the mean sea level. If the implementation cannot provide altitude information, the value of this attribute must be null.
     
  • The accuracy attribute denotes the accuracy level of the latitude and longitude coordinates. It is specified in meters and must be supported by all implementations. The value of the accuracy attribute must be a non-negative real number.
     
  • The altitudeAccuracy attribute is specified in meters. If the implementation cannot provide altitude information, the value of this attribute must be null. Otherwise, the value of the altitudeAccuracy attribute must be a non-negative real number.
     
  • The heading attribute denotes the direction of travel of the hosting device and is specified in degrees, where 0° ≤ heading < 360°, counting clockwise relative to the true north. If the implementation cannot provide heading information, the value of this attribute must be null. If the hosting device is stationary (i.e. the value of the speed attribute is 0), then the value of the heading attribute must be NaN.
     
  • The speed attribute denotes the magnitude of the horizontal component of the hosting device's current velocity and is specified in meters per second. If the implementation cannot provide speed information, the value of this attribute must be null. Otherwise, the value of the speed attribute must be a non-negative real number.

 

 

Concerning error handler, the code attribute must return the appropriate code from the following list:

  • PERMISSION_DENIED (numeric value 1)  - The location acquisition process failed because the document does not have permission to use the Geolocation API.
     
  • POSITION_UNAVAILABLE (numeric value 2) - The position of the device could not be determined. For instance, one or more of the location providers used in the location acquisition process reported an internal error that caused the process to fail entirely.
     
  • TIMEOUT (numeric value 3) - The length of time specified by the timeout property has elapsed before the implementation could successfully acquire a new Position object.

 

 

If you have read through the HTML code, you will realize that we are not only using the getCurrentPosition() method but also the watchPosition() method. Therefore, what is the difference between them? The watchPosition() method returns the current position of the user and continues to return updated position as the user moves (like the GPS in a car). That is why in order not to see some null values returned by this method, you need an accurate GPS device to test this (like a smartphone with GPS).

 

 

 

I hope you find this blog post about geolocation interesting and stay tuned for my upcoming blog posts! The next one will probably be about mapping using HTML5.

Outcomes