I am storing the data from an API call in variables and I would like to use the data in the variables elsewhere in the function. However, when I printout what is in the variables outside of the arrow function, the data has a type of undefined.
The first console.log(coordinates);
displays ["08002", "39.916258", "-75.021428"]
and the second displays
[
"08002",
"39.916258",
"-75.021428"
]
But when I have console.log(coordinates[1]);
outside of the arrow function it says it's undefined
.
const getLongLat = function(zip) { //gets long lat from a zip code
zip = document.getElementById("ZipCode").value
let lat = 0;
let long = 0;
let coordinates = [];
if (zip == "") {
zip = "08002"
}
coordinates.push(zip);
const APIkey = "#########";
let base = `http://open.mapquestapi.com/geocoding/v1/address?
key=${APIkey}&location=${zip}`;
console.log("base " + base);
fetch(base)
.then(response => response.json())
.then(data => {
//makes it so that the city is in the us
let i = 0;
while (data.results[0].locations[i].adminArea1 != "US") {
i++
}
lat = String(data.results[0].locations[i].latLng.lat);
long = String(data.results[0].locations[i].latLng.lng);
coordinates.push(lat);
coordinates.push(long);
console.log(coordinates);
})
console.log(coordinates);
return coordinates;
};