Search code examples
javascriptphpjqueryweather-api

how to integrate the generated link by wunderground.com into my website


in fact I am a beginner in the field of API and this is the first time I registered on wunderground.com, and I follow the documentation to generate the key ID. later I found links and codes.

Forecast in French

PHP:

<?php $json_string = file_get_contents("http://api.wunderground.com/api/2ea138a9dd52eabe    /geolookup/conditions/q/IA/Cedar_Rapids.json");
$parsed_json = json_decode($json_string);
$location = $parsed_json->{'location'}->{'city'};
$temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
echo "Current temperature in ${location} is: ${temp_f}\n"; ?>

Javascript & Jquery:

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
 <script> jQuery(document).ready(function($) {
 $.ajax({
 url : "http://api.wunderground.com/api/2ea138a9dd52eabe/geolookup/conditions  /q/IA/Cedar_Rapids.json", dataType : "jsonp", success : function(parsed_json) {
 var location = parsed_json['location']['city'];
 var temp_f = parsed_json['current_observation']['temp_f'];
 alert("Current temperature in " + location + " is: " + temp_f);
 } }); }); </script>

Have a wonderful day


Solution

  • Wunderground can be integrated using differend kind of methods.

    You have provide two separated ones: one from PHP and another from JavaScript. Both are equivalent, but implemented in different technologies.

    Javascript

    You can use JavaScript snipplet to load forecast on-the-fly. This way you have to insert fetched data in DOM hierarchy in place, where you need it. Replace your alert() call with something more appropriate. E.g.:

    $("#weather").empty().append ("Current temperature in " + location + " is: " + temp_f);
    

    You should create block/inline-element with "weather" id somewhere in document:

    <div id="weather">Loading forecast...</div>
    

    PHP

    Another way is to insert weather data from PHP side. This way you should output forecast directly into div:

    <div id="weather"><?php "Current temperature in ${location} is: ${temp_f}\n"; ?></div>