Did you find this useful?
Socialize it today.


HTML5 Geolocation

Monday, November 05, 2012

Web applications that deal with location can directly benefit from knowing exactly where the visitor to their site is located. That is where Geolocation enters the picture. Geolocation is the process of figuring out where you are in the world. With the diversity of client access to your site, there is more than one way to figure out where you user is located. Some of those methods include the visitor's IP address, cell tower the mobile device is communicating with, and/or a dedicated GPS hardware component that calculates latitude and longitude information.


Can it be disabled?

Privacy is an important concern when you are considering the process of sharing your physical location with a remote web server. Fortunately, the geolocation API states: "User Agents must not send location information to Web sites without the express permission of the user." Therefore the user agent (browser/client app) is required to request permission before obtaining the user's location.


Geolocation API

Geolocation is not a new HTML element, but is an API that allows you share your location with a web site. The information is gathered in the form of latitude and longitude data which are available to JavaScript. The geolocation API is supported by most modern browsers such as Internet Explorer 9, Firefox, Chrome, Safari and Opera. It is not supported by earlier versions of Internet Explorer.


Basic Example

The geolocation API focuses on a new property on the global navigator object: navigator.geolocation. Here is a simple example of how to use this API:



function getLocation() {
  navigator.geolocation.getCurrentPosition(showPosition);
}


getCurrentPosition()

The getCurrentPosition() method returns an object if it is successful. The latitude, longitude and accuracy properties are always returned. The other properties below are returned if available.


PropertyDescription
coords.accuracyThe accuracy of the position
coords.altitudeThe altitude in meters above the mean sea level
coords.altitudeAccuracyThe altitude accuracy of the position
coords.headingThe heading as degrees (clockwise from the North position)
coords.latitudeThe latitude as a decimal
coords.longitudeThe longitude as a decimal
coords.speedThe speed in meters per second
timestampThe date/time of the response


Only three of the properties are guaranteed to be available. The three properties are coords.latitude, coords.longitude, and coords.accuracy. The remainder of the properties may or may not have values, depending on the capabilities of the user's device.



The previous example is too simple. As mentioned earlier, not all browsers will support this API, or an error may occur while determining the location. It is suggested that we first test if the browser supports Geolocation services and if it does, let's make sure that we can also handle possible errors that may occur.

<button onclick="getLocation()">Get My Location</button>
<div id="Geo"></div>
<script>
var x=document.getElementById("Geo");
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="The user denied the request for Geolocation."
      break;
    case error.POSITION_UNAVAILABLE:
      x.innerHTML="The location information is not available."
      break;
    case error.TIMEOUT:
      x.innerHTML="The request to get the user location timed out."
      break;
    case error.UNKNOWN_ERROR:
      x.innerHTML="An unknown error occurred."
      break;
    }
  }
}
</script>





Display the Location in a Map

To display the result in a map, you need access to a map service that can use latitude and longitude. In the following example above we use the returned latitude and longitude data to show the location in a Google map.



<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Geolocation Example</title>
<style>
#map1 {margin-top:15px;border:1px solid #7f7f7f;box-shadow:1px 1px 10px #7f7f7f;visibility:hidden;}
</style>
</head>
<body>
<div id="demo">Click the button to get your location!
<button onclick="getLocation()">Get My Location!</button></div>

<div id="map1"></div>
<script src="http://maps.googleapis.com/maps/api/js?v=3.9&sensor=false"></script>
<script>
    var x = document.getElementById("demo");
    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition, showError);
            document.getElementById("map1").style.visibility = "visible";
        }
        else { x.innerHTML = "Geolocation is not supported by this browser."; }
    }

    function showPosition(position) {
        lat = position.coords.latitude;
        lon = position.coords.longitude;
        latlon = new google.maps.LatLng(lat, lon)
        myMap = document.getElementById('map1')
        myMap.style.height = '480px';
        myMap.style.width = '640px';

        var myOptions = {
            center: latlon, zoom: 14,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapTypeControl: false,
            navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL }
        };
        var map = new google.maps.Map(document.getElementById("map1"), myOptions);
        var marker = new google.maps.Marker({ position: latlon, map: map, title: "You are here!" });
    }

    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 not available."
                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>





Please help us spread the word by socializing it today!

email contact us

Did you find something wrong with the information on this page? Please take a moment to report it to us so that we can continue to improve the quality of the information on this site. Click here to report an issue with this page.



Recommended Books & Training Resources

HTML CSS and JavaScript Head First HTML5 Programming: Building Web Apps with JavaScript Murachs HTML5 and CSS3