I need to interchangeably get the user's geolocation and output the latitude/longitude coordinates into text fields. These must be in unique functions, as they will be used by different functionality interchangeably. Most importantly, the functions should run synchronously because the values used by the second function are made available by the first function.
Being new to both geolocation and async functions I'm not entirely sure which part below is broken, as the code below is a combination of many different tutorials used.
The requirement is to:
- Get the user's geo-coordinates (on-demand)
- Save these to a page-level variable
- Output the geo-coordinates into a text field (on-demand)
let latField = document.getElementById("EventSearch_Latitude");
let longField = document.getElementById("EventSearch_Longitude");
let myLocation = null;
// Get the user's geo-coordinates
async function GetMyLocation() {
console.log("Determining position");
myLocation = null;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
myLocation = position;
console.log("Position determined");
},
() => {
console.log("Geolocation is not supported by this browser, or was denied.");
}
);
} else {
console.log("Geolocation is not supported by this browser, or was denied.");
}
return Promise.resolve(1);
}
// Put the geo-coordinates into text fields
async function OutputMyLocation() {
console.log("OutputMyLocation()");
latField.value = "";
longField.value = "";
if (myLocation != undefined && myLocation != null) {
latField.value = myLocation.coords.latitude;
longField.value = myLocation.coords.longitude;
}
console.log("End OutputMyLocation()");
return Promise.resolve(1);
}
// Runs on page load
GetMyLocation()
.then(() => {
console.log(myLocation);
OutputMyLocation();
});
<p>
Latitude
<input type="text" id="EventSearch_Latitude" name="EventSearch.Latitude" value="">
</p>
<p>
Longitude
<input type="text" id="EventSearch_Longitude" name="EventSearch.Longitude" value="">
</p>
I'm not sure if StackOverflow allows navigator.geolocation.getCurrentPosition
, but in my local console I get this output:
Determining position
null
OutputMyLocation()
End OutputMyLocation()
Position determined
It appears (to me) that OutputMyLocation()
is not waiting for GetMyLocation()
to finish, so the script is trying to output the geo-coordinates before they've been determined. From the tutorials I read I had assumed that using Promise.resolve
and then
would overcome this.
What is my mistake please?