Search code examples
javascriptxmlhttprequestweatherweather-api

Whats the easiest way to create a weather-forecast?


Im developing an web app. Here I created a popup-window in JavaScript. Now I like to create inside this window a weather-forecast.

What is the easiest way to do this?

I did it like here: Get weather from Yahoo with jQuery

$(".popup-button").click(function(evt){
//prevent default link behavior
    evt.preventDefault();

//get id from clicked element
var id = $(this).attr("id");

switch (id) {
    case "popup-button-wetter":
        //centering with css
        centerPopup($("#popup-wrapper-wetter"));
        //load popup  
        loadPopupadditional($("#popup-wrapper-wetter"));
        //get weather
        getWeather ()
        break;
          ......


function getWeather () {
     $.get("http://weather.yahooapis.com/forecastrss?w=782458&u=c", function(data){
                   console.log("Data Loaded: " + data);
                 });
            }
    });

but then I got this error:

XMLHttpRequest cannot load http://weather.yahooapis.com/forecastrss?w=782458&u=c. Origin file:// is not allowed by Access-Control-Allow-Origin.

What does it mean?


Solution

  • I know I'm late, but I ran into the same problem when I was building a weather page. I used Google's API, but you should be able to rewrite this for Yahoo's API rather easily:

    Do something like this in a PHP file:

    <?php
    $lat = explode(".", $_GET["lat"] * 1000000); //latitude returned by JS geolocation
    $lon = explode(".", $_GET["lon"] * 1000000); //longitude returned by JS geolocation
    $api = simplexml_load_string(utf8_encode(file_get_contents("http://www.google.com/ig/api?weather=,,," . $lat[0] . "," . $lon[0] . "&zoom=10&hl=de")));
    echo $api->weather->current_conditions->temp_c->attributes()->data; //prints the current temperature in °C
    ?>
    

    Then set the charset of your HTML page to UTF-8 by inserting

    <meta charset="utf-8">
    

    into the <head> tag in order to correctly display umlauts like ä, ö and ü.

    Tl;dr: You can bypass the cross domain AJAX block by grabbing the XML file via PHP and then sending an XMLHttpRequest to your local PHP file. ;)