Search This Blog

Showing posts with label HTML5. Show all posts
Showing posts with label HTML5. Show all posts

Thursday, March 27, 2014

Summary and code samples for GPS calls and detection :HTML5

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

Use the watchPosition () method to get the user's position. The example below is a simple Geolocation example returning the latitude and longitude of the user's position:

if (navigator.geolocation) {
    navigator.geolocation.watchPosition(function (pos) {
     
       var lat = pos.coords.latitude;
        var lng = pos.coords.longitude; 
        if (lat != 0) {
            $("#lat").val(lat);// Assign hidden input field
            $("#lng").val(lng); // Assign hidden input field
        }
    });
}
else {
   
    alert( "Geolocation is not supported by this browser.");
   
}

Note : Add this code inside  <script> .....</script>  tag in your page

Example explained:
  • Check if Geolocation is supported
  • If supported, run the watchPosition() method. If not, display a message to the user
  • If the watchPosition () method is successful, it returns a coordinates object to the function specified in the parameter (pos)
  • The pos () function gets the displays the Latitude and Longitude

Handling Errors and Rejections:

For Handling Error We can use below code.
navigator.geolocation.getCurrentPosition(success, error, options);
var options = {
    enableHighAccuracy: true,
    timeout: 50000,
    maximumAge: 0
};

function success(pos) {
    var crd = pos.coords;
};

function error(err) {
    alert('ERROR(' + err.code + '): ' + err.message);

};