The watchPosition()
method of the Geolocation interface is used to register a handler function that will be called automatically each time the position
of the device changes. You can also, optionally, specify an error handling callback function.
This method retrieves periodic updates about the current geographic location of the device, allows to detect a change in position of device. The location object contains geographic coordinates with information about speed.
Like we have 3 parameters in getCurrentPosition()
method, watchPosition()
accepts the same:
-
success
: A callback function that retrieves the location information. -
error
(Optional): An optional callback function that takes a GeolocationPositionError object as an input parameter. -
options
(Optional): This optional parameter specifies a set of options for retrieving the location information.You can specify:
- Accuracy of the returned location information
- Timeout for retrieving the location information
- Use of cached location information
Return value
: An integer ID that identifies the registered handler.
The ID can be passed to the Geolocation.clearWatch()
to unregister the handler and stop receiving location updates.
Example Code:
function onSuccess(position) { //do something with position data. console.log("Latitude: " + position.coords.latitude); console.log("Longitude: " + position.coords.longitude); } function onError(error) { switch(error.code) { case error.PERMISSION_DENIED: console.log("User denied the request for Geolocation."); break; case error.POSITION_UNAVAILABLE: console.log("Location information is unavailable."); break; case error.TIMEOUT: console.log("The request to get user location timed out."); break; case error.UNKNOWN_ERROR: console.log("An unknown error occurred."); break; } } // Options: throw an error if no update is received every 30 seconds. var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 });
Thank you for giving this useful information! It conveyed important details in a brief and engaging manner. I look forward to more valuable postings like this. Keep Reading…
ReplyDeleteMBA Colleges in Tamilnadu with Fees Structure - SKIMT
Great insights on using the Geolocation API! It's fascinating how this technology enhances user experience by providing location-specific services. As a Digital Marketing Agency in Coimbatore, we understand the importance of integrating such features to improve engagement and drive conversions. Thanks for sharing this valuable information!
ReplyDeleteThis tutorial on the JS Geolocation API is super helpful! Using watchPosition() feels as streamlined as coding with Fira Code—both ensure clarity and precision in your work.
ReplyDelete