Skip to content Skip to sidebar Skip to footer

Why Spread Syntax Can't Work In Navigator's Position Object?

The Position object can't work with spread syntax navigator.geolocation.getCurrentPosition((position) => { console.log(position); for( var i in position) { console.log

Solution 1:

Spread syntax only expands to the the object's own enumerable properties. The properties of Position are defined using getters in the prototype, they're not ordinary, own properties in the object itself.

If you do console.log(Object.keys(position)) it will show an empty array for the same reason.

for-in iterates over the object's enumerable properties, it's not restricted to own properties. So it includes the inherited properties. So you'll have to do the shallow copy with a loop:

d = {}
for (i in position) {
  d[i] = position[i];
}

Solution 2:

First of all, realise that the default timeout for getCurrentPosition is infinite(!). That means that your error handler will never be called if getCurrentPosition hangs somewhere on the back end.

To ensure that you get a timeout, add the optional third parameter to your call to getCurrentPosition, for example, if you want the user to wait no more than 10 seconds before giving them a clue what is happening, use:

navigator.geolocation.getCurrentPosition(successCallback,errorCallback,{timeout:10000});

Due to timeout reason may be you are not able to get the output of position. Once you get position data, you may try like:

    navigator.geolocation.getCurrentPosition(function(position) {
        console.log(position);
        var lat = position.coords.latitude;
        var lng = position.coords.longitude;
    }, function(error) {
       console.log(error);
    });

Once above code works properly, you may convert them into arrow function and able to use your code.

Post a Comment for "Why Spread Syntax Can't Work In Navigator's Position Object?"