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