Apache Cordova | Phonegap Geolocation Tutorial

Phonegap / Apache Cordova geo loaction api tutorials
Phonegap / Apache Cordova geo location api tutorials
Phonegap / Apache Cordova geo location api tutorials

Phonegap Geolocation Tutorial with Google Maps API

What you’ll Learn from this tutorial ?

  1. Geolocation with phonegap
  2. How to get GPS (Geolocation) position using phonegap / apache cordova
  3. Learn how to integrate google maps in phonegap applications

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 org.apache.cordova.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>