This is a discussion on Flash CS3 and Yahoo Weather within the Tutorials forums, part of the Flash English category; We saw how load an external XML file with Actionscript 3.0 and also how to work with a RSS ...
We saw how load an external XML file with Actionscript 3.0 and also how to work with a RSS and Flash CS3 to create a titles slide.
Today, we will see how to use a free Yahoo service to retrieve the data of the worldcities weather prevision.
This service, named Yahoo Weather, gives us a RSS which is nothing else then an XML file.
Basically:
We call a script placed on the Yahoo server and we pass to it the "id" city and a value "c" (for centigrade) or "f" (for Fahrenheit) and Yahoo returns an XML file with the value for the chosen city.
Let us see how to do it"
I create a FLA and save it as "main.fla".
Into which, I create four levels from top to bottom:
- code: into which I add the codes seen next
- testo: a dynamic text field named "title_txt"
- logo: a MovieClip named "yahoo_mc" containing the Yahoo logo
- area: a TextArea component named "info_ta"
On the keyframe of the level "code", I write:
Code:
var location_id:String='ITXX0148';
var grades:String='c';
var url:String='http://weather.yahooapis.com/forecastrss"p='+location_id+'&u='+grades;
var richiesta:URLRequest=new URLRequest();
var loader:URLLoader;
richiesta.url=url;
richiesta.method=URLRequestMethod.GET;
loader=new URLLoader();
addListeners(loader);
try
{
loader.load(richiesta);
}
catch (error:Error)
{
trace('Unable to load requested document.');
}
function addListeners(d:IEventDispatcher):void
{
d.addEventListener(Event.COMPLETE,completato);
}
function completato(evt:Event):void
{
var vars:URLVariables=new URLVariables(evt.target.data);
var r:XML=new XML(evt.target.data);
var myXML:XMLDocument=new XMLDocument();
myXML.ignoreWhite=true;
myXML.parseXML(r.toXMLString());
var node:XMLNode=myXML.firstChild.firstChild;
title_txt.text=node.firstChild.firstChild.nodeValue;
var n:int=int(node.childNodes.length);
for(var i:int=0;i < n;i++)
{
if(node.childNodes[i].nodeName=='item')
{
var s:int=int(node.childNodes[i].childNodes.length);
for(var j:int=0;j < s;j++)
{
if(node.childNodes[i].childNodes[j].nodeName=='description')
info_ta.htmlText=node.childNodes[i].childNodes[j].firstChild.nodeValue;
}
}
}
}
yahoo_mc.buttonMode=true;
yahoo_mc.addEventListener(MouseEvent.CLICK,go);
function go(evt:MouseEvent):void
{
var request:URLRequest=new URLRequest('http://weather.yahoo.com/');
navigateToURL(request,'_blank');
}
The result:
Let us analyse the code
A string variable into which I insert the value of the chosen city. To find out the id of a city, you can directly see it from the site Yahoo Weather
var location_id:String='ITXX0148';
a string variable into which I insert "c" or "f" based on the unit of measure I wish to use
var grades:String='c';
a string variable into which I insert the url of the Yahoo script to call. I also pass to it the two variables "location_id" and "grades"
var url:String='http://weather.yahooapis.com/forecastrss"p='+location_id+'&u='+grades;
an URLRequest variable which will request the url
var richiesta:URLRequest=new URLRequest();
an URLLoader which will call the server side script and retrieve the returned values
var loader:URLLoader;
I request the url
richiesta.url=url;
I impost the type request to GET (this Yahoo service only accepts the GET request)
richiesta.method=URLRequestMethod.GET;
I instantiate the URLLoader
loader=new URLLoader();
I call the function addListeners
addListeners(loader);
I call the script
try
{
loader.load(richiesta);
}
catch (error:Error)
{
trace('Unable to load requested document.');
}
I add a listener to the event COMPLETE which will call the function "completato" so that we can retrieve the value passed by the script
function addListeners(d:IEventDispatcher):void
{
d.addEventListener(Event.COMPLETE,completato);
}
In the next function, I apply a logic to retrieve the XML data returned by Yahoo. Those data and information offer many options and I chose to use only a few of them. If you are interested to retrieve all or some other values from the XML, you can study the XML format from http://developer.yahoo.com/weather/
function completato(evt:Event):void
{
var vars:URLVariables=new URLVariables(evt.target.data);
var r:XML=new XML(evt.target.data);
var myXML:XMLDocument=new XMLDocument();
myXML.ignoreWhite=true;
myXML.parseXML(r.toXMLString());
var node:XMLNode=myXML.firstChild.firstChild;
title_txt.text=node.firstChild.firstChild.nodeValu e;
var n:int=int(node.childNodes.length);
for(var i:int=0;i < n;i++)
{
if(node.childNodes[i].nodeName=='item')
{
var s:int=int(node.childNodes[i].childNodes.length);
for(var j:int=0;j < s;j++)
{
I assign the needed data in HTML format to the TextArea component using its htmlText property
if(node.childNodes[i].childNodes[j].nodeName=='description')
info_ta.htmlText=node.childNodes[i].childNodes[j].firstChild.nodeValue;
}
}
}
}
Next is the logic which control the click on the Yahoo logo
yahoo_mc.buttonMode=true;
yahoo_mc.addEventListener(MouseEvent.CLICK,go);
function go(evt:MouseEvent):void
{
var request:URLRequest=new URLRequest('http://weather.yahoo.com/');
navigateToURL(request,'_blank');
}
It is working fine when I test this on my local machine, but when i test this on the server and view on the internet, it seems like it's not grabbing the results from yahoo?
This is the code of the php file I have:
forecastrss.php
This is the code of the actionscript I have:
scripts/content.as
Code:
// import the event dispatcher class
import mx.events.EventDispatcher;
// init values
var xml_components_to_load = 0;
var xml_components_loaded = 0;
// intialize event dispatcher
EventDispatcher.initialize(this);
this.addEventListener("containerInit",getContent);
this.addEventListener("xmlInit",getContent);
// create a new array to hold the data
weatherDays = new Array();
var weatherDayIndex = 0;
// event controller function - this function processes all events
function getContent(evt){
// everything is ready to load RSS data from source
if(evt.type=="containerInit"){
// create data provider and begin loading from data source
contentDP = new XML();
contentDP.ignoreWhite = 1;
contentDP.load(feedURL);
// make call to function when the data has completed loading
contentDP.onLoad = loadRSSWeather;
xml_components_to_load++;
}
if(evt.type=="xmlInit"){
xml_components_loaded++;
if(xml_components_loaded==xml_components_to_load){
}
}
}
// load the XML from the RSS feed
function loadRSSWeather(){
// The following parsing algorithm is made specifically for the Yahoo Weather RSS feed.
// The parser looks for the exact path to the weather data we are looking for:
// rss.channel.item.{yweather:condition, yweather:forecast}
xmlData = this.firstChild.firstChild.childNodes;
todaysWeather = new Weather();
for(var i=0; i0){
if(itemData[j].nodeName.indexOf("condition")>0){
// this is the current conditions
// attach weatherDay from library and pass all tag attributes from data source
obj = _root.attachMovie("weatherDay","todaysWeather",getNextHighestDepth(),itemData[j].attributes);
weatherDays.push(obj);
}else if(itemData[j].nodeName.indexOf("forecast")>0){
// this is part of the forecast
// attach weatherDay from library and pass all tag attributes from data source
obj = _root.attachMovie("weatherDay","forecastWeather_"+j,getNextHighestDepth(),itemData[j].attributes);
obj._visible = 0;
weatherDays.push(obj);
}
}
}
}
}
dispatchEvent({type:"xmlInit", target:this});
}
// function to check the next day's weather (and make the appropriate movieclip visible)
function nextWeatherDay(){
weatherDays[weatherDayIndex]._visible = 0;
if(++weatherDayIndex>weatherDays.length-1){
weatherDayIndex = 0;
}
weatherDays[weatherDayIndex]._visible = 1;
}
// function to check the prev day's weather (and make the appropriate movieclip visible)
function prevWeatherDay(){
weatherDays[weatherDayIndex]._visible = 0;
if(--weatherDayIndex<0){
weatherDayIndex = weatherDays.length-1;
}
weatherDays[weatherDayIndex]._visible = 1;
}
This is the action I have set in flash:
Code:
// go to http://weather.yahoo.com, find the page for the city you
// want to use and then copy the link to the RSS feed. make sure you
// grab the RSS link and not the link to the HTML page. it should look
// something like this...
feedURL = "http://xml.weather.yahoo.com/forecastrss?p=CAXX0343&u=c";
// include the script to grab the XML data and import it into the flash movie
#include "scripts/content.as"
// fire event to display current weather conditions
dispatchEvent({type:"containerInit", target:this});
// when button is pressed, shift it's position
function btnPressed(btn) {
btn._x += 1;
btn._y += 1;
}
// when button is released, put it back
function btnReleased(btn) {
btn._x -= 1;
btn._y -= 1;
}
Any ideas why its not pulling results from yahoo properly? it shows in the web browser as though its trying to pull from yahoo?
The link: Untitled Document