Geolocation using Advanced HTML 5

Geolocation is a feature in HTML5 which enables browsers to determine the geographical position of a user. For privacy reasons, geolocation is disabled by default in all supporting browsers. Users have to explicitly give permission to the browser before their position can be determined.

The geolocation API is published through the navigator.geolocation object.

Retrieving the current position

To obtain the user’s current location, you can call the getCurrentPosition() method. This initiates an asynchronous request to detect the user’s position, and queries the positioning hardware to get up-to-date information. When the position is determined, the defined callback function is executed. You can optionally provide a second callback function to be executed if an error occurs

Example

In the following example, the Get Location button triggers a call to the getCurrentPositon method. Once the call to getCurrentPosition() is complete  longitude and latitude are updated on the form and the view map link will open a new window with google maps.

<!doctype html>
<html lang="en">
    <head>
        <title>Geolocation</title>
        <link rel="stylesheet" href="/global.css" type="text/css"/>
        http://../scripts/jquery-1.6.2.js
        </head>
    <body>

Show Position

 

View Map Latitude Longitude

     

    /scripts/Geolocation.js </body> </html>

    $(function() {
    
        var mapLink = $("#mapLink");
        var log = $("#log");
    
        $("#getLocationButton").click(function() {
            navigator.geolocation.getCurrentPosition(showPosition, positionError);
        });
    
        function showPosition(position) {
    
            var coords = position.coords;
    
            $("#lat").val(coords.latitude);
            $("#long").val(coords.longitude);
            
            mapLink.attr("href", "http://maps.google.com/maps?q="
            + $("#lat").val() + ",+" +
                $("#long").val() + "+(You+are+here!)&iwloc=A&hl=en"
            );
            mapLink.show();
    
        }
    
        function positionError(e) {
            switch (e.code) {
                case 0:
                    logMsg("The application has encounterd an unknown error");
                    break;
                case 1:
                    logMsg("You chose not to allow this applicaiton to access your location");
                    break;
                case 2:
                    logMsg("The application was unable to determine your location");
                    break;
                case 3:
                    logMsg("The request to determine your location has timed out.");
                    break;
                
            default:
            }
        }
    
        function logMsg(msg) {
            log.append("<li>" + msg + "</li>");
        }
    })

    Links