HTML5 Geolocation

Geo-location is a new feature that has been included in HTML5. It allows the viewer to share his current location to trusted servers or websites. Once the location is determined, the server can then use this data to do a lot of stuff. Imagine creating a HTML application that determines the location of all your favorite food corners near you say in a 5 kilometer radius.  With the new Geo-location feature it is possible, cool isn’t it.


Geo-Location API

The Geo-location facility is provided by the all new and important Geo-Location API in HTML5. What happens primarily is that the latitude and longitude of the user is available to JavaScript in the page which can send the values to a remote server and then do location fancy stuff.

Lets look at a quick example of how to do so,

The Geo-location API adds a new property to the global navigator object navigator.geolocation.

navigator.geolocation.getCurrentPosition(success,error);

Next thing to do is to call the getCurrentPosition() method as shown, inside your JavaScript function to determine the location. For eg.

function getLocation()
{
navigator.geolocation.getCurrentPosition(success,error);
}

where success and error are references of two callback methods.

Note that Geo-location feature is optional, so the browser will never force you to provide your physical location to a remote server, instead it will prompt you to provide the same. The prompt varies from browser to browser. In Firefox an info-bar appears at the top similar to the one that you might have seen when it tries to open a pop-up window and you have disabled the feature in your browser. In the info-bar you will have options to either share your location or decline the current request.

Ok, coming back to the code, I have mentioned two callback methods success and error. You might have guessed it by now, that success is called when you have agreed to share your location. It is where we will write the code for doing the location fancy stuff. while error is called when you have declined to share your location. You can display custom message in this method.

On Success

The success method looks like this.

function success(position)
{
var lat = position.coords.latitude; //this is for latitude
var lng = position.coords.longitude; //this is for longitude
}

The function takes as parameter the position object which is a part of the geo-location API. The position object has two properties coords and timestamp. Within coords, properties such as latitude and longitude have been defined which are the important ones that we require. Also as the name suggests, timestamp determines the data and time when the location was determined.

Full Example

Lets see a full example.

<!DOCTYPE html>

<html>
<head>
    <title>Geolocation Demo</title>
    <style type="text/css">

        body
        {
            padding:20px;
        }

        #mapHolder
        {
            width:700px;
            height:400px;
            border:1px solid #9a9a9a;
        }
    </style>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript" src="js/jquery-1.6.1.min.js"></script>
    <script type="text/javascript">

        $(document).ready(function(){

            $("#locationBtn").click(function(){
                if(navigator.geolocation) //browser supports geolocation
                    navigator.geolocation.getCurrentPosition(success,error);
                else
                    alert("Your browser does not support HTML5 geolocation");
            });
        });

        //if the user shares his location, plot his location on a map
        function success(position)
        {
              $("#status").text("Finding location......");

              var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
              var mapOptions = {
                zoom: 10,
                center: latlng,
                mapTypeControl: false,
                mapTypeId: google.maps.MapTypeId.ROADMAP
              };

            var map = new google.maps.Map(document.getElementById("mapHolder"), mapOptions);

            //plot a marker
            var markerOptions = {
                  position: latlng,
                  map: map,
                  title:"My location"
            };
            var marker = new google.maps.Marker(markerOptions);

            $("#status").text("Location found!");
        }

        //if the user declines to share his location
        function error(msg)
        {
            $("#status").text("You have denied to share your location");
        }

    </script>
</head>
<body>
    <input type="button" id="locationBtn" value="Locate on Map" />
    <div id="mapHolder">

    </div>
    <span id="status"></span>
</body>
</html>

Demo link : http://jsphkhan.github.io/html5_geolocation/

Source: https://github.com/jsphkhan/jsphkhan.github.io/tree/master/html5_geolocation

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s