OpenWeather API - Pulling JSON data out

47,796

I have the basics that should help you on your way. It's a mashup of your two pages.

First I amended your getWeather function to call for the weather rather than the forecast. It accepts a city parameter and appends that parameter to the data before the callback is called.

function getWeather(city, callback) {
  var url = 'http://api.openweathermap.org/data/2.5/weather';
  $.ajax({
    dataType: "jsonp",
    url: url,
    jsonCallback: 'jsonp',
    data: { q: city },
    cache: false,
    success: function (data) {
        data.city = city;
        callback(data);
    }
  });
}

Here, in lieu of your teams JSON I made one up in the form of a JS object, with Arsenal and Liverpool and their corresponding cities as the data. The function loops over the object, extracts the city name and passes it to getWeather. The data is returned and appended to the div.

$(document).ready(function () {

  $("#btn382").click(function () {

    var teams = {
      arsenal: { city: 'london' },
      liverpool: { city: 'liverpool' }
    };

    for (var team in teams) {
      var city = teams[team].city;
      getWeather(city, function(data) {
        var html = [];
        html.push('<div>')
        html.push('City: ', data.city, ', ');
        html.push('Lat: ', data.coord.lat, ', ');
        html.push('Lon: ', data.coord.lon, ', ');
        html.push('Weather: ', data.weather[0].description);
        html.push('</div>')
        $("#div381").append(html.join('')).css("background-color", "orange");
      });
    }

  });
});

Hopefully this will give you a few ideas about how to tackle this project.

See it working here.

Share:
47,796
Grimlockz
Author by

Grimlockz

Updated on July 29, 2020

Comments

  • Grimlockz
    Grimlockz almost 4 years

    I'm writing a little JavaScript to pull information from JSON that contains name, longitude, latitude and openweather API call. What I need is to get the API information out of the API call into the HTML page so you can get the weather forecast for each information. I have the two elements working separately but can't work out how to get them working together.

    Help please? :-)

    Sample API Weather from d.weather

     api.openweathermap.org/data/2.5/forecase?lat=50.8609&lon=-0.08014&&units=metric
    

    HTML page for pulling the openweather JSON data

    <html>
    <head>
    <title>Weather</title>
        <meta charset="utf-8">
    
        <script src="http://code.jquery.com/jquery-1.7.min.js" ></script>
        <script src="http://code.jquery.com/ui/1.7.0/jquery-ui.js" ></script>
    
    <script>
    function getWeather(callback) {
        var weather = 'http://api.openweathermap.org/data/2.5/forecast?lat=51.5072&lon=0.1275&units=metric';
        $.ajax({
          dataType: "jsonp",
          url: weather,
          success: callback
        });
    }
    
    // get data:
    getWeather(function (data) {
        console.log('weather data received');
        console.log(data.list[0].weather[0].description); 
        console.log(data.list[0].weather[0].main);  
    });
    
    getWeather(function (data) {
        document.write('weather data received');
        document.write('<br>');
        document.write(data.list[0].weather[0].description);
        document.write('<br>');
        document.write(data.list[0].weather[0].main);
        document.write('<br>');
        document.write(data.list[0].main.temp);
        document.write('<br>');
        document.write(data.list[0].main[0].dt_txt);
        document.write('<br>');
    });
    </script>
    </body>
    </html>
    

    Html page for pulling the JSON data

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script> 
    <!-- Javascript -->
    
    <script type="text/javascript">
    function loadUrl(newLocation){
        window.location = newLocation;
        return false;
    }
    </script>
    
    <script type="text/javascript">
    $(document).ready(function (){
        $("#btn382").click(function(){       
            /* set no cache */
            $.ajaxSetup({ cache: false });
    
            $.getJSON("weather.json", function(data){
                var html = [];
    
                /* loop through array */
                $.each(data, function(index, d){           
                    html.push("Team : ", d.Teams, ", ",
                              "Long : ", d.Long, ", ",
                              "Lat : ", d.Lat, ", ",
                  "Weather : ", d.Weather, "<br>");        
                });
    
    
                $("#div381").html(html.join('')).css("background-color", "orange");
            }).error(function(jqXHR, textStatus, errorThrown){ /* assign handler */
                /* alert(jqXHR.responseText) */
                alert("error occurred!");
            });
        });
    });
    </script>
    
    <!-- HTML -->
    <a name="#ajax-getjson-example"></a>
    <div id="example-section38">   
        <div>Football weather</div>
        <div id="div381"></div>
        <button id="btn382" type="button">Team location</button>
    </div>
    

    weather.json

    {
        "Teams":"Wycombe Wanderers",
        "Long":-0.800299,
        "Lat":51.6306,
        "Weather":"  api.openweathermap.org/data/2.5/weather?lat=51.6306&lon=-0.800299&mode=html"
      },
      {
        "Teams":"Livingston",
        "Long":-3.52207,
        "Lat":55.8864,
        "Weather":"  api.openweathermap.org/data/2.5/weather?lat=55.8864&lon=-3.52207&mode=html"
      },
      {
        "Teams":"Brighton and Hove Albion",
        "Long":-0.08014,
        "Lat":50.8609,
        "Weather":"  api.openweathermap.org/data/2.5/weather?lat=50.8609&lon=-0.08014&mode=html"
      },
    
    • Andy
      Andy over 10 years
      Can you add these to a jsfiddle?
    • Andy
      Andy over 10 years
      Wait, where are you getting teams from? That won't be in the weather data. Do you mean city?
    • Grimlockz
      Grimlockz over 10 years
      Hi Andy, teams are coming from json file which I have manually entered that field
    • Andy
      Andy over 10 years
      But somewhere here you seem to merging the weather json and the team json, but I don't see where that's happening.
    • Grimlockz
      Grimlockz over 10 years
      I have the two html working in theory as separate pages, team json should be the manual file from the second html page whereas weather json is the api data call I believe
    • Andy
      Andy over 10 years
      How are the two sets of data related? Are you linking the teams and weather by city? Until you know that, you won't be able to loop through the datasets to access the information. And for each team you'll need to do a separate API call to get the weather for that city.
    • Grimlockz
      Grimlockz over 10 years
      I think I have the weather function working in the first html page which pulls data from the api url so I was hoping that as I have the api url in the other html page I could merge the first function into the second page? maybe?
    • t.niese
      t.niese over 10 years
      @Grimlockz Just a note: I would suggest not to call the open weather api directly but to cache the results yourself on your server. That would make your service more stable an reliable.
  • Grimlockz
    Grimlockz over 10 years
    Andy thanks for all your help I can see what you have and its a great help - I've added the weather.json so you can see what I was trying to do
  • Andy
    Andy over 10 years
    If this is the best answer, can you click the tick?
  • Andy
    Andy over 10 years
    @Grimlockz, I've updated the fiddle with code related to the team info you added. I haven't updated the answer.
  • Grimlockz
    Grimlockz over 10 years
    amazing - thanks for your help on this - I love jsfiddle.net btw
  • Mr. Concolato
    Mr. Concolato over 9 years
    Because JSON is much faster to parse. Almost 10 times the efficiency.
  • sakher
    sakher over 9 years
    Any proofs that JSON is faster
  • Mr. Concolato
    Mr. Concolato over 9 years
    Here is an experiment in Python that illustrates my statement: github.com/concolato/data_processing/tree/master/…, and since Python is a C based language, I would expect similar results in C/C++, Java and PHP. But, you can try it in another language to confirm if you like.