108
Watch (and follow) the current position of the device with Geolocation API
2021-06-30 - JavaScript
1// JS Tip of the Day
2// Watch the current position of the device with Geolocation API
3
4let geoWatcher;
5const geoTarget = { lat: 37.869186, long: 41.275438 };
6const options = { enableHighAccuracy: true, timeout: 2000, maximumAge: 0 };
7
8function success({ coords }) {
9 if (geoTarget.lat === coords.latitude.toFixed(6)
10 && geoTarget.long === coords.longitude.toFixed(6)) {
11
12 console.log(`I'Batman! :D`);
13 navigator.geolocation.clearWatch(geoWatcher);
14 }
15}
16
17function error(err) {
18 console.warn(`Error: ${err.code} - ${err.message}`);
19}
20
21if (window.navigator && window.navigator.geolocation) {
22 geoWatcher = navigator.geolocation.watchPosition(success, error, options);
23}
#JStipoftheday