I'm using the following code to get a users location using watchPosition . I would also like to define code for the fail parameter and pass options to watchPosition
, but I'm not sure where the code should go.
if (navigator.geolocation) {
//Success callback defined, but where shouls fail & options go?
var positionTimer = navigator.geolocation.watchPosition((position) => {
var crd = position.coords;
console.log("Updated user loc...");
console.log(crd.latitude + " : " + crd.longitude);
this.myLatitude = crd.latitude;
this.myLongitude = crd.longitude;
this.updateUserLocation();
},
console.warn("Error getting user location"),
this.options);
}
else {
alert("Geolocation not supported in your browser!");
}
Here's what you want:
const positionTimer = navigator.geolocation.watchPosition(
(position) => {
// Your success code here
console.log(position);
},
(err) => {
// Your error code here
console.log(err);
},
{
// Options here
}
)
Just remember:
An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.
Source: Arrow functions
You can use them just like you would use a normal function
the things that change are just the mentioned above.
You could also declare your arrow functions:
const success = (position) => { /* Success code here */ }
const error = (err) => { /* Error code here */ }
const options = { /* Options... */ }
const positionTimer = navigator.geolocation.watchPosition(success, error, options);
Here you go:
const options = {}; const id = navigator.geolocation.watchPosition((pos) => { console.log(pos); }, (err) => { console.log(err); }, options)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.