Getting current geo location details of the mobile device using PhoneGap (Cordova)

 The PhoneGap library provide lot of useful functionalities for accessing native mobile features like Camera, Geo location, Voice recorder etc., In this tutorial I am going to collect current Geo location details of the mobile device using Geolocation methods available in PhoneGap (Cordova).
 PhoneGap (Cordova) provides two different methods for getting geo location details. Those are,

            1. geolocation.getCurrentPosition - Returns the current position as Position object.
            2. geolocation.watchPosition - It continuously watch changes of device 's current position.

 The example for above methods are shown here.
navigator.geolocation.getCurrentPosition(geoLocationSuccess,geoLocationError,{timeout:30000});
(or)
navigator.geolocation.watchPosition(geoLocationSuccess,geoLocationError,{timeout : 30000});

function geoLocationSuccess(position) {
 var str = 'Latitude: '          + position.coords.latitude          + '\n' +
           'Longitude: '         + position.coords.longitude         + '\n' +
           'Altitude: '          + position.coords.altitude          + '\n' +
           'Accuracy: '          + position.coords.accuracy          + '\n' +
           'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
           'Heading: '           + position.coords.heading           + '\n' +
           'Speed: '             + position.coords.speed             + '\n' +
           'Timestamp: '         + position.timestamp                + '\n' ;
 alert(str);

}

function geoLocationError(error) {
 alert('code: '    + error.code    + '\n' + 'message: ' + error.message + '\n');
}
 Here the first parameter indicates your success callback function, second parameter indicates your failure callback and final parameter indicates various options that are provided by PhoneGap (Cordova), those are,
  1. maximumAge - Accept a cached position whose age is no longer than given timeout (in milliseconds)
   2. timeout
   3. enableHighAccuracy - Either true or false.

 There is one more method available for stopping watch position function. The example is show here.
var watchId = navigator.geolocation.watchPosition(geoLocationSuccess,geoLocationError,{ timeout: 30000 });
navigator.geolocation.clearWatch(watchId);
 You can find more example from PhoneGap (Cordova) documentation.
Hope this help..!

Comments