Geolocation Doesn't Run the Function Passed to It

Geolocation Doesn't Run the Function Passed to It
0

#1

I’m trying to get the user’s coordinates for the Local Weather Project. I have this:

var x = 1;

function userCoords() {
    navigator.geolocation.getCurrentPosition(function(pos) {
        x = 2;
});
}

If I check x's value in the console before calling userCoords, it’s 1, as expected. When I call userCoords, Firefox prompts me for my location, I say yes, and there are no errors, but when I check x’s value, it’s still 1.

I searched the forum, but no one else seems to be having trouble with this. How can I fix it? The example provided with the assignment doesn’t work for me either, it just sits there.

edit: I should mention that I’m currently editing my files in emacs and opening the html with Firefox manually. I used to use CodePen, but it lagged too much. When I was using CodePen, it was with https, but geolocation didn’t work then either.


#2

Hey. The .getCurrentPosition() method is asynchronous. Meaning that javascript will continue its execution without waiting for the getCurrentPosition() to finish. Therefore, the value of x won’t be changed in time. What you can do is call a function inside the method and then use your new data as you wish.

function userCoords() {
 navigator.geolocation.getCurrentPosition(function(pos) {
    x = 2
    useData(x);
 });
}
function useData(x) {
  console.log(x); // 2
}

#3

Thanks for replying.

I tried the code you provided (adding var x = 1) at the top, but calling userCoords still doesn’t seem to do anything. My output in the console is:

>> x
1
>> userCoords()
undefined // <-- Doesn't print?
>> x
1

edit: I just cp’d the html and jQuery example from here and it works… perfectly? Though I still want to know why geolocation’s not working for me, for future refence.


#4

geolocation does not work in the console - the page has to be served with https


Problem getting geolocation information in local weather
#5

Sorry, could you elaborate?