I'm trying to write a set of functions that call the openstreetmaps API and parse out the country code, then append that to a URL to update window.location. I've figured out how to use async fetch in order to get to the point where I can return the country code properly, but the URL on the reloaded page, instead of showing the country code, says [object%20Promise]. I'm trying to figure out why it's not sending back just the country code and is sending the promise. I've googled and can't seem to find anything about returning a value from an async fetch, so I'm assuming I'm doing something wrong.
<script>
async function countryCode(lat, long)
{
var buildURL = 'https://nominatim.openstreetmap.org/reverse?lat=' + lat + '&lon=' + long + '&format=json&zoom=3';
var twoLetterCode = await fetch(buildURL)
.then(response => {
return response.json();
})
.then(data => {var jsonData = data;
var addressInfo = jsonData.address;
var code = addressInfo.country_code
return code;
});
console.log(`Code is: ` + twoLetterCode);
return twoLetterCode;
}
function getLocation(){
navigator.geolocation.getCurrentPosition(function(position) {
let mapJson = countryCode(position.coords.latitude, position.coords.longitude);
window.location = window.location.href.split('?')[0] + "?lat=" + position.coords.latitude + "&lon=" + position.coords.longitude + "&loc=" + mapJson;
});
}
</script>