Watches for changes to the device's current position.
var watchId = navigator.geolocation.watchPosition(geolocationSuccess, [geolocationError], [geolocationOptions]);
geolocation.clearWatch
to stop watching for changes in position.Function geolocation.watchPosition
is an asynchronous function. It returns the device's current position when a change in position has been detected. When the device has retrieved a new location, the geolocationSuccess
callback is invoked with a Position
object as the parameter. If there is an error, the geolocationError
callback is invoked with a PositionError
object.
// onSuccess Callback // This method accepts a `Position` object, which contains // the current GPS coordinates // function onSuccess(position) { var element = document.getElementById('geolocation'); element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' + 'Longitude: ' + position.coords.longitude + '<br />' + '<hr />' + element.innerHTML; } // onError Callback receives a PositionError object // function onError(error) { alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n'); } // Options: retrieve the location every 3 seconds // var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { frequency: 3000 });
<!DOCTYPE html> <html> <head> <title>Device Properties Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); var watchID = null; // PhoneGap is ready // function onDeviceReady() { // Update every 3 seconds var options = { frequency: 3000 }; watchID = navigator.geolocation.watchPosition(onSuccess, onError, options); } // onSuccess Geolocation // function onSuccess(position) { var element = document.getElementById('geolocation'); element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' + 'Longitude: ' + position.coords.longitude + '<br />' + '<hr />' + element.innerHTML; } // onError Callback receives a PositionError object // function onError(error) { alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n'); } </script> </head> <body> <p id="geolocation">Watching geolocation...</p> </body> </html>