← Plugins / Geolocation
This official Apache Cordova plugin reads the device's current GPS position and lets you subscribe to location changes as the user moves. Its interface mirrors the W3C Geolocation API, so the methods and the data they return will feel familiar if you have used geolocation in the browser.
Add the plugin to your Cordova project from the command line:
cordova plugin add cordova-plugin-geolocation
The plugin attaches its methods to navigator.geolocation. Call them after the deviceready event has fired:
| Method | Description |
|---|---|
navigator.geolocation.getCurrentPosition(success, error, options) | Fetches a single, one-shot reading of the device's current position. |
navigator.geolocation.watchPosition(success, error, options) | Returns a watch id and keeps calling success each time the device moves. |
navigator.geolocation.clearWatch(watchId) | Stops the active watch identified by watchId. |
The success callback receives a position object whose location data lives under coords:
| Property | Type | Description |
|---|---|---|
coords.latitude | Number | Latitude in decimal degrees. |
coords.longitude | Number | Longitude in decimal degrees. |
coords.altitude | Number | Height above sea level in metres. |
coords.accuracy | Number | Accuracy of the latitude and longitude, in metres. |
coords.altitudeAccuracy | Number | Accuracy of the altitude reading, in metres. |
coords.heading | Number | Direction of travel in degrees, measured clockwise from north. |
coords.speed | Number | Current ground speed in metres per second. |
timestamp | Number | When the reading was taken, as a millisecond timestamp. |
Pass an options object to tune how the position is read:
| Property | Type | Description |
|---|---|---|
enableHighAccuracy | Boolean | Request the most precise fix the device can provide. |
timeout | Number | How long, in milliseconds, to wait for a reading before failing. |
maximumAge | Number | Accept a cached fix up to this many milliseconds old. |
Read the device's current location once and log the coordinates:
navigator.geolocation.getCurrentPosition(onSuccess, onError, {
enableHighAccuracy: true
});
function onSuccess(position) {
console.log("Lat: " + position.coords.latitude);
console.log("Lng: " + position.coords.longitude);
}
function onError(error) {
console.log("Code: " + error.code);
console.log("Message: " + error.message);
}
deviceready — the plugin isn't available before then.clearWatch when leaving a screen so the GPS keeps running no longer than necessary.