Question

In: Computer Science

1. Write the code to show the current weather based on geolocation. I am stuck and...

1. Write the code to show the current weather based on geolocation. I am stuck and cant figure out how to show the weather. My current code is below. Please try and use OpenweatherAPI.  

<!DOCTYPE html>

<html>

  <head>

    <title>Weather</title>

    <link

      rel="stylesheet"

      href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/bootstrap.css"

    />

    <link rel="stylesheet" href="main.css" />

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

    <script type="text/javascript" src="app.js"></script>

  </head>

  <body>

    <div class="jumbotron">

      <button onclick="getLocation()">Get my location.</button>

      <p id="demo"></p>

      <script>

        var x = document.getElementById("demo");

        function getLocation() {

          if (navigator.geolocation) {

            navigator.geolocation.getCurrentPosition(showPosition);

          } else {

            x.innerHTML = "Geolocation is not supported by this browser.";

          }

        }

        function showPosition(position) {

          x.innerHTML =

            "Latitude: " +

            position.coords.latitude +

            "<br>Longitude: " +

            position.coords.longitude;

        }

      </script>

      <p>The weather outside is:</p>

      <div class="weather">

        Oops.. there is no temperature available for your location right now.

      </div>

    </div>

  </body>

</html>

Solutions

Expert Solution

<!DOCTYPE html>
<html>
   <head>
      <title>Weather</title>
      <link
         rel="stylesheet"
         href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/bootstrap.css"
         />
      <link rel="stylesheet" href="main.css" />
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
      <script type="text/javascript" src="app.js"></script>
   </head>
   <body>
      <div class="jumbotron">
         <button onclick="getLocation()">Get my location.</button>
         <p id="demo"></p>
         <script>
           var x = document.getElementById("demo");

         function getLocation() {

             if (navigator.geolocation) {

                 navigator.geolocation.getCurrentPosition(showPosition);

             } else {

                 x.innerHTML = "Geolocation is not supported by this browser.";

             }

         }

         function showPosition(position) {
             x.innerHTML =
                 "Latitude: " +
                 position.coords.latitude +
                 "<br>Longitude: " +
                 position.coords.longitude;
             getWeatherData(position.coords.latitude, position.coords.longitude);

         }

         // takes data object as input
         function showWeather(data) {
             // finds the temperature in celcius ,
             // temperature is inside main and as temp,
             // you can check the response json to clearly understand this
             var temperature = Math.round(parseFloat(data.main.temp) - 273.15);

             // gets the current weather discription
             var description = data.weather[0].description;

             // finally sets the resulting data in the div with id weather,
             document.getElementById('weather').innerHTML = temperature + '&deg;,' + description;
         }

         // takes latitude,longitude and longitude as parameters
         function getWeatherData(latitude, longitude) {
             // TODO: set your api key here
             var api_key = ;

             // fetches weather data using latitude,longitude with passing the api_key and then
             // response is converted into json and resulting object is passed into
             // showWeather() function to display the data
             fetch('https://api.openweathermap.org/data/2.5/weather?lat=' + latitude + '&lon=' + longitude + '&appid=' + api_key)
                 .then(function(response) {
                     return response.json()
                 }) // convert resonse to json
                 .then(function(data) {
                     showWeather(data);
                 })
                 .catch(function() {
                     // if there is any errors catch the error
                     alert("Error Occured !")
                 });
         }
         </script>
         <p>The weather outside is:</p>
         <div class="weather" id="weather">
            Oops.. there is no temperature available for your location right now.
         </div>
      </div>
   </body>
</html>

Before you run this , make sure to get an api key from OpenweatherAPI and setting the variable api_key inside getWeatherData() function to the api key that you have got from it,also if you get a 401 error,then wait sometime to get the api key activated, if you just created an account,it took around 10 minutes to get api key activated for me,i have not done any styling,also i added an id to the div "weather" to access it using getElementById

Output:

PS-:If you have any doubts/problems please comment below.Thank you


Related Solutions

I am stuck on this problem and I am not sure what the solution is. In...
I am stuck on this problem and I am not sure what the solution is. In C Write item.h and item.c. In item.h, typedef a struct (of type t_item) which contains the following information: t_item: char name[MAX_ITEM_NAME_STRING]; char description[MAX_ITEM_DESCRIPTION_STRING]; Make sure that MAX_ITEM_NAME_STRING and MAX_ITEM_DESCRIPTION_STRING are defined with suitable sizes in your item.h. Typical values are, 25 and 80, respectively. Add the following interface definition to item.h: int item_load_items(t_item items[], int max_items, char *filename); Returns the number of objects loaded...
Hello! I am stuck on the following question: Show that every simple subgroup of S_4 is...
Hello! I am stuck on the following question: Show that every simple subgroup of S_4 is abelian.
Hi! I am in an intro level Finance course and I am stuck on this problem....
Hi! I am in an intro level Finance course and I am stuck on this problem. Any help would be greatly appreciated. I am deciding on opening a restaurant. I was able to scrape together some capital from friends and family, but I must pay them back in 4 years at 12% per annum. I figure that it will cost me $165,000 to start up with rent, deposits, equipment, salaries, chicken, basil, rice, etc. for the first year, but I...
Hello! I am stuck on only B-1 Recession EPS - I got everything else and I...
Hello! I am stuck on only B-1 Recession EPS - I got everything else and I cannot figure out what I'm doing wrong - I keep getting $4.81, but it's incorrect and I don't know why. Can you help? I pasted my numbers below the question. Sunrise, Inc., has no debt outstanding and a total market value of $240,900. Earnings before interest and taxes, EBIT, are projected to be $40,000 if economic conditions are normal. If there is strong expansion...
I am stuck on approaching the answer to this question, and most of the answer that...
I am stuck on approaching the answer to this question, and most of the answer that I have found online and on Chegg are do not make any sense regarding this question. What would be a good interpretation of what this question is asking regarding the GDP? "Think about the increases since 2001 in spending for the Department of Homeland Security and the wars in Afghanistan and Iraq. These increases represent government expenditures that have increased GDP. Explain whether you...
Kind of stuck on this one with the JE. Need to know if I am on...
Kind of stuck on this one with the JE. Need to know if I am on the right track with this problem. Please help Thomas sells products that carry a 6-month manufacturer’s warranty. Customers have the opportunity at the time of purchase to also buy a 3 year extended warranty for an additional charge of $100. Thomas sold 1,000 units this year for $2,000 each. For this year’s sales, Thomas estimates the 6-month warranty costs to be 10% of sales....
I am stuck in Austin with a flat tire, and I need to get to my...
I am stuck in Austin with a flat tire, and I need to get to my class in Houston within 2 hours. The drive is 180 miles long, but I want to be careful of the Austin cops. I do not usually get caught speeding unless I am seen accelerating too fast, so I do not want to accelerate at a rate of more than 120 mi?/?h2. Just to be careful, I?m going to take exactly 2 hours to make...
I am trying to write a code in C for a circuit board reads in a...
I am trying to write a code in C for a circuit board reads in a temperature from a sensor on the circuit board and reads it onto a 7-segment LED display. How exactly would you code a floating 2 or 3 digit reading onto the LED display? I am stuck on this part.
Java ArrayList Parking Ticket Simulator, Hello I am stuck on this problem where I am asked...
Java ArrayList Parking Ticket Simulator, Hello I am stuck on this problem where I am asked to calculate the sum of all fines in the policeOfficer class from the arraylist i created. I modified the issueParking ticket method which i bolded at the very end to add each issued Parking ticket to the arrayList, i think thats the right way? if not please let me know. What I dont understand how to do is access the fineAmountInCAD from the arrayList...
Write assembler code to print even numbers from 1-20. Submit code and screenshot. I am coding...
Write assembler code to print even numbers from 1-20. Submit code and screenshot. I am coding in NASM on a SASM system.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT