Help With Functions Fetch

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>

Please post your code so that we cn see what yu are working on. Thanks

1 Like

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.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like
  • 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.

fetch(URL)
  .then((response) => response.json())
  .then((data) => {
    render(data);
  });


function render(weatherData) {
  const city = weatherData.name;
  const { temp } = weatherData.main;

  HTML = `
  <section>
    <h2>${city}</h2>
    <h4>${temp}</h4>
  </section>
  `;

  document.querySelector("body").insertAdjacentHTML("beforeend", HTML);
}

BTW, you really don’t want to post API keys in public.

1 Like

I will take note of your suggestions. Thank you!

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);


'''

Did you look in the console and network tab in the browser developer tools?

Do you see any errors?

What is getting logged out?


Do you have the key= parameter for the API key?

From the docs

https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_API_KEY
1 Like

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.

404 suggests to me that you are not hitting the correct endpoint.

Try logging out the URL you are building and make sure it is in the correct format. I would also suggest you add https:// to the URL as well.

1 Like

I will try it out. Thanks!