I was trying to fetch some JSON data from a google map API. When I called this function, I want the "test" variable to become 45. But it is still 0.
This following code looks a little bit stupid because I want to simplify things. I have a valid API key please don't question that. Did I misunderstand Javascript or the fetch api or something? Please help.. Thanks a lot!
function toLat(location) {
var lat = 0;
if (location.length > 0) {
var googleURL = "https://maps.googleapis.com/maps/api/geocode/json?address=Seattle&key=Your_API_Key";
fetch(googleURL)
.then(function(response) {
return response.json();
})
.then(function(data) {
data.results.forEach(function(item) {
lat = item.geometry.location.lat;
});
console.log(lat); // here is, e.g. '45'
});
}
return lat;
}
var test = toLat();
console.log(test); // why still '0'?