Cordova - Geolocation
Cordova - Geolocation
Section titled “Cordova - Geolocation”The Geolocation plugin provides access to the device’s location using GPS, Wi-Fi, or cellular network signals. You can get the device’s current latitude and longitude, and also track changes in its position over time.
Step 1 - Installing the Geolocation Plugin
Section titled “Step 1 - Installing the Geolocation Plugin”Install the plugin using the Cordova CLI. Open your terminal or command prompt, navigate to your project’s root directory, and run:
your-cordova-project/ cordova plugin add cordova-plugin-geolocationNote: This plugin requires user permission to access location data. The plugin will typically handle prompting the user, but ensure your app’s privacy policy reflects its use of location services.
Step 2 - Add UI Elements (Optional)
Section titled “Step 2 - Add UI Elements (Optional)”For this tutorial, we’ll add buttons to trigger geolocation functions. Add the following HTML to your index.html file:
<body> <button id="getCurrentPositionBtn">Get Current Position</button> <button id="watchPositionBtn">Watch Position</button> <div id="locationInfo">Location data will appear here.</div></body>Step 3 - Add Event Listeners
Section titled “Step 3 - Add Event Listeners”In your www/js/index.js file, within the onDeviceReady function, add event listeners for these buttons:
// Inside onDeviceReady in www/js/index.jsdocument.getElementById("getCurrentPositionBtn").addEventListener("click", getCurrentPosition);document.getElementById("watchPositionBtn").addEventListener("click", startWatchPosition);Step 4 - Implement Geolocation Functions
Section titled “Step 4 - Implement Geolocation Functions”Now, let’s define the functions to get and watch the position. We’ll also create a helper to display the data.
const locationDisplay = document.getElementById('locationInfo');let watchID = null; // To store the ID for watchPosition
// Options for geolocation requestsconst geolocationOptions = { enableHighAccuracy: true, // Request more accurate position (can consume more power) timeout: 10000, // Maximum time (in ms) to wait for a position maximumAge: 60000 // Maximum age (in ms) of a cached position that is acceptable};
function getCurrentPosition() { navigator.geolocation.getCurrentPosition(onSuccess, onError, geolocationOptions);}
function startWatchPosition() { if (watchID) { // Clear previous watch if any navigator.geolocation.clearWatch(watchID); } // Start watching for position changes // The success callback will be invoked repeatedly as the position changes. watchID = navigator.geolocation.watchPosition(onSuccess, onError, geolocationOptions); locationDisplay.innerHTML = 'Watching for location changes...';}
function onSuccess(position) { const Scoords = position.coords; locationDisplay.innerHTML = `Latitude: ${coords.latitude}<br/>` + `Longitude: ${coords.longitude}<br/>` + `Altitude: ${coords.altitude}<br/>` + `Accuracy: ${coords.accuracy}m<br/>` + `Altitude Accuracy: ${coords.altitudeAccuracy}m<br/>` + `Heading: ${coords.heading}<br/>` + `Speed: ${coords.speed}<br/>` + `Timestamp: ${new Date(position.timestamp).toLocaleString()}`;}
function onError(error) { let errorMsg = 'Error getting location: '; switch (error.code) { case error.PERMISSION_DENIED: errorMsg += 'User denied the request for Geolocation.'; break; case error.POSITION_UNAVAILABLE: errorMsg += 'Location information is unavailable.'; break; case error.TIMEOUT: errorMsg += 'The request to get user location timed out.'; break; case error.UNKNOWN_ERROR: errorMsg += 'An unknown error occurred.'; break; } locationDisplay.innerHTML = errorMsg; console.error(errorMsg, error);}When you click the “Get Current Position” button, the onSuccess callback will (ideally) display the device’s current geolocation data in the locationInfo div. For example, it might show: “Latitude: 34.0522, Longitude: -118.2437…”.
Clicking the “Watch Position” button will continuously update the location data in the locationInfo div as the device moves or as more accurate readings become available. The timeout option in geolocationOptions means that if a position isn’t retrieved within 10 seconds, the onError callback will be triggered.
Important Considerations
Section titled “Important Considerations”- User Permissions: Always handle cases where the user denies permission for location access.
- Accuracy vs. Power:
enableHighAccuracy: trueprovides better accuracy but consumes more battery. Set it tofalseif high accuracy is not critical. - Error Handling: Implement robust error handling as shown in the
onErrorfunction. Location services can fail for various reasons. - Clearing Watch: It’s crucial to call
navigator.geolocation.clearWatch(watchID)when you no longer need to track the position (e.g., when the user navigates away from the relevant screen) to save battery. - Background Location: Tracking location in the background requires additional setup and permissions, and is subject to platform restrictions.
For more detailed information on geolocation options and potential issues, refer to the official cordova-plugin-geolocation documentation and the W3C Geolocation API Specification.