My First Weather Project

I am open to suggestions. This is my link:

Hi @santiagodeleondecar1 !

My only suggestion would be to maybe have a default weather showing in the event the user does not allow the browser to allow access to their location.

That way at least a weather is showing on load.

2 Likes

I appreciate your comment really.

I get an invalid API key error. Not sure if you revoked it or what?

For an app like this, if you need the API keys to be private you need a backend.


I would remove the image repeat and set the size to cover.

background-repeat: no-repeat;
background-size: cover;
1 Like

I will implement this. Thanks!. I did not know that this was possible. Please, you have something more to share, donÂŽt doubt about it.

I have a question, how can I know if the server is installed correctly? I use Sublime.

I can’t really answer that. It is installed correctly if you can use it, and it works if you can use it (like starting it and logging something out). The editor doesn’t matter.

1 Like

I have been having too many problems with the terminal and I donÂŽt know what to do. I cannot access the variables and I cannot install npm init -y.

What variables, environment variables?
The video I posted goes over it.

What happens when you run npm init -y?
It just creates a package.json file then you can install the dependencies npm i somePackageName.

1 Like

I do not understand the reason why my code does not run properly clearly.

The program marks error when I set require(“dotenv”).config() and let appId=process.env.API_KEY does not work either;

/*AIzaSyDE0yJyoQ5kSbOD3H9XGYB2NNBAXc9vPvs*/


/*const http = require("http");

require("dotenv").config()
const PORT = process.env.PORT||5000
);






app.listen(PORT,() => console.log(`Server running on port ${PORT}`))

require("dotenv").config();

let port = process.env.PORT;
let host = process.env.HOST;




server.listen(port, host, ()=>{
       console.log(`Server is listening ${host}:${port}`);
});*/



const options = { 
  enableHighAccuracy: true,
  timeout:5000,
  maximunAge: 0

};

function success (pos){
  const crd = pos.coords;
  let link = "https://maps.googleapis.com/maps/api/geocode/json?latlng="; 
  let latitude = crd.latitude;
  let longitude = crd.longitude;
  let googleKey="&key=KEY"; 
  let completeLink= link +latitude+","+longitude+googleKey 
  



 console.log(completeLink)
      fetch(completeLink)
      .then(response=>response.json())
      .then(data=>{
        
        console.log(data);
        let city = data["results"]["5"]["address_components"][2]["long_name"];

        console.log(city);
        document.querySelector(".city").innerText = "Weather in " + city;
         let beginningOfTheLink="https://api.openweathermap.org/data/2.5/weather?q=";
        //let appId = "&appId=KEY"
         let appId=process.env.API_KEY;
         let metricUnit="&units=metric";
         let newLink=beginningOfTheLink+city+appId+metricUnit;
         console.log(newLink) 
         
        fetch(newLink)
        .then(info=>info.json())
        .then(tempInfo=>{
          
          let icon = tempInfo["weather"][0]["icon"];
          console.log(icon) 
          let temp = tempInfo["main"]["temp"];
          console.log(temp)
          
          let yourButton=document.getElementById("yourButton");
         yourButton.addEventListener("click",yourFunction)
          console.log(tempInfo)
          
          let myButton = document.getElementById("myButton");
          myButton.addEventListener("click",myFunction)
          console.log(temp)
           


          function yourFunction(){
                 document.querySelector(".temp").innerText=Math.round(temp)+" ÂșC"; 
                 document.querySelector(".icon").src = "http://openweathermap.org/img/wn/"+icon+"@2x.png";
           }

                      function myFunction(){
                 let fahrenheit = Math.round(temp) + 32;
                 
                 
                 document.querySelector(".temp").innerText=fahrenheit+" ÂșF"
                 document.querySelector(".icon").src = "http://openweathermap.org/img/wn/"+icon+"@2x.png";
                 
                 
           }


           })
        })
      

     }
   


function error(err){
  console.warn(`ERROR(${err.code}): ${err.message}`);
  }


navigator.geolocation.getCurrentPosition(success,error,options);
require("dotenv").config()
        //console.log(process.env);

This my .env file

HOST = localhost
PORT = 1234
API_BASE_URL="https://maps.googleapis.com/maps/api/geocode/json?latlng="
API_KEY_NAME="appid"
API_KEY = "&appId=KEY"
/*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 = "&key=KEY";
    let completeLink = link+coordinates+myGoogleKey;

          console.log(completeLink);
    fetch(completeLink)
        .then(response=>response.json())
        .then(data=>console.log(data))   

     

} */

I don’t know what I’m looking at. You have a mix of frontend and backend code. I have removed anything that looked like an API key as you do not want to post that in public. Or at least, if you do you have to remember to revoke the keys after you have gotten the help.

Please format your code and post the front and backend code separately as you have it now.

If you want to hide the API keys using a backend, the backend will have to do the fetching and send the data it gets back to your client. So your client will fetch against your own backend.

1 Like

Thanks!

I think it has a better order now and I have erased the keys.

It keeps telling me this when I run it: uncaught ReferenceError: require is not defined in weather app

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device">
	<link rel="stylesheet" type="text/css" href="Main.css">
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
	
	<title>GeoLocation app</title>

</head>
<body>
	<div class="card">
		<div class="search">
			
			<button id="yourButton" class="fa-solid fa-circle-c"><i class="fa-solid fa-circle-c" >ÂșC</i></button>
			<button id="myButton" class="fa-solid fa-circle-c"><i class="fa-solid fa-circle-c" >ÂșF</i></button>
		    </div>
		    <div class = "weather">
			<h2 class="city">Weather in</h2>
			<h1 class="temp"></h1>
			<img src ="" alt="" class="icon"/>
			

	</div>
<script>
	const express = require('express');//uncaught ReferenceError: require is not defined in weather app
const app = express();
app.listen(3000, () => console.log('listening at 3000'));
app.use(express.static('public'));


const options = { 
  enableHighAccuracy: true,
  timeout:5000,
  maximunAge: 0

};

function success (pos){
  const crd = pos.coords;
  let link = "https://maps.googleapis.com/maps/api/geocode/json?latlng="; 
  let latitude = crd.latitude;
  let longitude = crd.longitude;
  let googleKey= 
  let completeLink= link +latitude+","+longitude+googleKey 
  



 console.log(completeLink)
      fetch(completeLink)
      .then(response=>response.json())
      .then(data=>{
        
        console.log(data);
        let city = data["results"]["5"]["address_components"][2]["long_name"];

        console.log(city);
        document.querySelector(".city").innerText = "Weather in " + city;
         let beginningOfTheLink="https://api.openweathermap.org/data/2.5/weather?q=";
        let appId = 
         
         let metricUnit="&units=metric";
         let newLink=beginningOfTheLink+city+appId+metricUnit;
         console.log(newLink) 
         
        fetch(newLink)
        .then(info=>info.json())
        .then(tempInfo=>{
          
          let icon = tempInfo["weather"][0]["icon"];
          console.log(icon) 
          let temp = tempInfo["main"]["temp"];
          console.log(temp)
          
          let yourButton=document.getElementById("yourButton");
         yourButton.addEventListener("click",yourFunction)
          console.log(tempInfo)
          
          let myButton = document.getElementById("myButton");
          myButton.addEventListener("click",myFunction)
          console.log(temp)
           


          function yourFunction(){
                 document.querySelector(".temp").innerText=Math.round(temp)+" ÂșC"; 
                 document.querySelector(".icon").src = "http://openweathermap.org/img/wn/"+icon+"@2x.png";
           }

                      function myFunction(){
                 let fahrenheit = Math.round(temp) + 32;
                 
                 
                 document.querySelector(".temp").innerText=fahrenheit+" ÂșF"
                 document.querySelector(".icon").src = "http://openweathermap.org/img/wn/"+icon+"@2x.png";
                 
                 
           }


           })
        })
      

     }
   


function error(err){
  console.warn(`ERROR(${err.code}): ${err.message}`);
  }


navigator.geolocation.getCurrentPosition(success,error,options);
</script>
</body>
</html>

You are still mixing frontend and backend code.

The express code runs on Node.js, not in the browser. I would suggest you go through some more learning material and get a better understanding of the differences between front and backend code.

Have you done the freeCodeCamp backend challenges? If not I would start there.


Or just forget about the backend for now and get it working in the browser without a backend. Then later you can learn more about Node/Express and try moving all the API fetch code to the backend. Then create frontend fetch code that fetches from your own Node/Express server.

1 Like

Thanks! I will start the backend challenges. I will write on this post later. I will take your advice.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.