0

I'm hoping someone with a lot more experience in JavaScript can help me because I think I am falling foul of asynchronous functions, variable scope and trying to figure out what to do. I have been through a number of answers on here but nothing helped me.

I am trying to get coordinates from the browser. This is code I found online which uses the browser:

<script>
    'use strict';
    var pos = '';
    //if there is no geo, use browser html 5
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            var geopos = {
                lng: position.coords.longitude,
                lat: position.coords.latitude
                }
            console.log(geopos);
            pos = geopos;
            });             
        }
    console.log(pos);

The first log shows the following: {lng: -0.76##########, lat: 51.6#########} which is perfect.

However the second log 'pos' is showing as nothing. Literally a blank line in the console.

I'm really hoping that I have made a really obvious and silly mistake, one of those head slapping moments because I cannot figure out why 'pos' is not coming through the scope of the function

I've researched into anonymous functions, callback, variable scope, and I cannot solve this. Please help.

N.B: I have a feeling the second log is being called before the first which would make the function call 'asynchronous'? But I don't know how to make that work for me.

Phfog
  • 75
  • 5
  • 3
    Your feeling is correct. getCurrentPosition is an asynchronous function https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition . Therefore you need to implement the sucess callback and only there you have your result available. – zelite Jun 29 '20 at 14:12
  • Thanks everyone for the comments and answers. It's a lot to look through. I will and then return with any feedback... – Phfog Jun 29 '20 at 14:22

2 Answers2

0

As you suspect, getCurrentPosition is asynchronous and will call your provided callback when done. So until that happens pos won't have a a usable value.

So any code that needs to be run with the current position must be run inside the callback, or after the callback has been called. So you could either add the code you need to run inside the callback, or if your code reacts to event you could simply check whether pos is set or not.

0

That's because the second is called before the first, as you noticed.

You should use it with wrapped in a promise and then wait for it:

const Position = () => {
    return new Promise(function (success, error) {
        navigator.geolocation.getCurrentPosition(success, error);
    });
};

then you can do:

var pos = await Position();
console.log(pos)

Now pos is defined ;)

Raffobaffo
  • 2,806
  • 9
  • 22