I want to access to let temperatura and let name from outside of my function, but I do not know how
<!DOCTYPE html>
<html>
<head></head>
<meta charset="utf-8">
<title></title>
<button onclick="findWeatherIn()" id="cambioDeClima">Clima en</button>
<input id="ciudad" value="Ciudad"></input>
<button id="plus32">Sumar 32</button>
<body>
<script>
function findWeatherIn(){
let callApi="https://api.openweathermap.org/data/2.5/weather?q=";
let city=document.getElementById("ciudad").value;
let apiId="&appid=fb7d1b30a7118355b40022d2ba41b9b6";
let celsius="&units=metric";
let URL=callApi+city+apiId+celsius;
fetch(URL)
.then(response => response.json())
.then(data=>{
let temperatura = data["main"]["temp"];
let name = data["name"];
})
}
</script>
</body>
</html>
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.
You can return the data out of the function (or the promise) and use it at the call site.
You can pass the data into a different function that does something with it.
You can create state (variables) outside the function (in an outer scope) that gets the data assigned. If you assign the data to variables scoped to the fetch/then functions you have to return them out or pass them to another function.
You can add the data to the DOM directly inside the fetch/then.
Hello! I do not understand the reason why I cannot fetch from Google Maps. I have used fetch before And I got results. I do not understand the reason why it is not working now.
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos){
const crd = pos.coords;
// console.log("Your current position is: ");
// console.log(` Latitude: ${crd.latitude}`);
// console.log(`Longitude: ${crd.longitude}`);
// console.log(`More or less ${crd.accuracy} meters.`);
let latitude = `${crd.latitude}`;
let longitude = `${crd.longitude}`;
let link = "maps.googleapis.com/maps/api/geocode/json?latlng=";
let coordinates = latitude+", "+longitude;
let myGoogleKey = "";//I keep private my Google Key
let completeLink = link+coordinates+myGoogleKey;
console.log(completeLink);
fetch(completeLink)
.then(response=>response.json())
.then(data=>console.log(data))
}
function error(err){
console.warn(`ERROR(${err.code}): ${err.message}`);
}
navigator.geolocation.getCurrentPosition(success, error, options);
'''
Hello! Yes, I am getting 404 not found in my console when I use fetch, but when I use the console, I get the correct link. I can copy and paste it at Google and I get the answer.
Byt I do not understand what is the reason why fetch is not working properly.