HTML getCurrentPosition

HTML getCurrentPosition
0

#1

I am having difficulty understanding why I cannot access the coordinates outside of the call back function of getCurrentPosition.

I want to pass these coordinates to the Distance Matrix API in Google Maps, to show how far the person viewing the website is from my location. But I cannot figure how to use the coordinates outside of the call back function.

Here is a demo:
https://codepen.io/mwilliams279/pen/mppVZY?editors=1011

And here is the JS code:

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {        
document.getElementById("demo").innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
     latlon = position.coords.latitude + "," + position.coords.longitude;
     document.getElementById("demo").innerHTML = latlon;         //this works
  return latlon;
}

alert(showPosition());                                                             //this does not work
document.getElementById("map").innerHTML = latlon;        //this does not work

#2

You don’t use them outside the callback function, because the navigator.geolocation.getCurrentPosition function is asynchronous. Asynchronous functions allow other code to continue running without waiting for the asynchronous function complete. This means your alert(showPosition()); line and the next line execute before the coordinates even come back. If you want to use the data received back from the API, then you must put the code inside the call back function.


#3

Thanks Randell, I appreciate your answer. I am new to understanding call back functions.
My idea is to use Google maps on my portfolio page so when I apply to internships it will show an estimated commute time from my neighborhood to their location.
I will try putting the code within the callback function.