cordova-plugin-geolocation
cordova plugin geolocation
cordova-plugin-geolocation

Cordova plugin Geolocation Tutorial

What you’ll Learn from this tutorial ?

  1. Geolocation with phonegap
  2. How to get GPS (Geolocation) position using phonegap / apache cordova

According to phonegap documentation,┬áThis plugin provides information about the device’s location, such as latitude and longitude. Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs. There is no guarantee that the API returns the device’s actual location.
Steps :

  1. Create your PhoneGap project and add your platform
  2. Add Geolocation plugin using
    cordova plugin add cordova-plugin-geolocation

There are three methods in geolocation plugin such as

  • navigator.geolocation.getCurrentPosition returns current GPS position
  • navigator.geolocation.watchPosition continuously watch GPS position
  • navigator.geolocation.clearWatch Clear all data

Objects:

  • Position
  • PositionError
  • Coordinates

Syntax

navigator.geolocation.getCurrentPosition(geolocationSuccess,[geolocationError],[geolocationOptions]);

Example :

navigator.geolocation.getCurrentPosition(onSuccess, onError);
var onSuccess = function(position) {
    alert('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');
};
function onError(error) {
    alert('code: '    + error.code    + 'n' +
          'message: ' + error.message + 'n');
}

phonegap geolocation plugin example


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Geo Location</title>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript">
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'<hr />' + element.innerHTML;
}
function onError(error) {
alert('code: ' + error.code + 'n' +
'message: ' + error.message + 'n');
}
</script>
</head>
<body>
<div id="geolocation"></div>
</body>
</html>
Sundaravel M

About the author: Hey! It's me sundar. (Yea, I'm the founder of codesundar.com). I'm a passionate computer programmer who loves modern web and mobile development. feel free to reach me : Facebook - Twitter - Google+