Learn App Making
with Ionic, Cordova & Flutter.

Start Here Buy Themes

Cordova Geolocation Plugin Tutorial

What you’ll learn from this tutorial?

  • Geolocation with PhoneGap
  • 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 :

Create your PhoneGap project and add your platform

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>