Comunidad de diseño web y desarrollo en internet online

Problema con API de yahoo weather

Citar            
MensajeEscrito el 01 Jul 2010 09:17 pm
Hola de nuevo!!!, estoy tratando de manioular la API de yahoo weather de este post: http://www.cristalab.com/tips/mostrar-el-clima-en-flash-con-el-api-yahoo-weather-para-as3-c75042l/ en flex 4, pero tengo un error con la palabra "this" que no lo puedo corregir tengo toda la mañana en esto y nada :S, aqui les dejo el codigo como lo tenia al principio:

Este es el error que me marca el compilador:

"Multiple markers at this line:
-1042: The this keyword can not be used in static methods. It can only be used in instance methods, function closures, and global code.
-Line breakpoint: tvrevista.mxml [line: 41]"

Código Flex :


<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
            xmlns:s="library://ns.adobe.com/flex/spark" 
            xmlns:mx="library://ns.adobe.com/flex/mx" width="1024" height="768">
   
   <fx:Script>
      <![CDATA[
         //importamos las clases necesarias 
         import com.yahoo.webapis.weather.WeatherService; 
         import com.yahoo.webapis.weather.Weather; 
         import com.yahoo.webapis.weather.events.WeatherErrorEvent; 
         import com.yahoo.webapis.weather.events.WeatherResultEvent; 
         import fl.data.DataProvider; 
         //cramos el servicio 
         var ws:WeatherService = new WeatherService(); 
         //var w:Weather = new Weather();    
         
         //escuchador cuando recivimos los datos 
         ws.addEventListener(WeatherResultEvent.WEATHER_LOADED, resultTiempo); 
         //si hay un error al recibir los datos 
         function xmlError(event:WeatherErrorEvent):void { 
            //weather_txt.text = event.data.toString(); 
         } 
         //error al leer el xml 
         ws.addEventListener(WeatherErrorEvent.XML_LOADING, xmlError); 
         // 
         //ACTION PARA ESTE EJEMPLO 
         // 
         var periodo:String; 
         var codigoEstado:int; 
         var miLoader:Loader = new Loader(); 
         var miReq:URLRequest=new URLRequest(); 
         var mes:Array; 
         var dia:Array; 

         //estados del tiempo en español 
         var xmlData:XML; 
         var xmlLoader:URLLoader = new URLLoader(); 
         var urlRequest:URLRequest = new URLRequest("clima-es.xml"); 
         xmlLoader.load(urlRequest); 


ERROR ------>  xmlLoader.addEventListener(Event.COMPLETE, this.iniciarXML); 


         var xmlList:XMLList = new XMLList(); 
         private function iniciarXML(e:Event):void { 
            xmlData = new XML(xmlLoader.data); 
            xmlList = XMLList(xmlData.clima); 
            init(); 
         } 
         //datos para el combo 
/*          var ciudades:Array = new Array({label:"Córdoba",data:"ARCA0023"},{label:"Buenos Aires",data:"ARBA0009"},{label:"Rio Cuarto",data:"ARCA0073"},{label:"Villa Carlos Paz",data:"ARCA0108"},{label:"Trevelin",data:"ARCT9203"},{label:"Azul",data:"ARBA0129"},{label:"Ushuaia",data:"ARTF0105"}); 
         var dp:DataProvider = new DataProvider(ciudades); 
         cb.dataProvider=dp; 
         cb.addEventListener(Event.CHANGE, cbSelect); 
         function cbSelect(o:Event):void { 
            ws.getWeather(cb.selectedItem.data, "metric"); 
         }  */
         
         function init() { 
            mes = new Array("Enero","Febrero","Marzo","Abril","Mayo","Junio","julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"); 
            dia = new Array("Domingo","Lunes","Martes","Miercoles","Jueves","Viernes","Sabado"); 
            time_txt.autoSize = TextFieldAutoSize.LEFT ; 
            contImgGde.y = time_txt.y+15; 
            
            ws.getWeather(MXJO0047, "metric"); 
            formatFecha(); 
         } 
         
         function formatFecha() { 
            var date:Date = new Date(); 
            var minutos:String; 
            if (date.getMinutes()<10) { 
               minutos = "0"+String(date.getMinutes()); 
            } else { 
               minutos = String(date.getMinutes()); 
            } 
            if (date.getHours()<12) { 
               periodo ="am"; 
            } else { 
               periodo ="pm"; 
            } 
            time_txt.text = dia[date.day]+" "+String(date.getDate() +" de "+mes[date.getMonth()]+" - "+date.getHours()+":"+minutos+" "+periodo); 
            
            var contDay:int = date.day; 
            switch (date.day) { 
               case 5 : 
                  estado1_txt.text = dia[6]; 
                  estado2_txt.text = dia[0]; 
                  break; 
               case 6 : 
                  estado1_txt.text = dia[0]; 
                  estado2_txt.text = dia[1]; 
                  break; 
               default : 
                  estado1_txt.text = dia[date.day+1]; 
                  estado2_txt.text = dia[date.day+2]; 
            } 
         } 
         
         function resultTiempo(event:WeatherResultEvent):void { 
            codigoEstado = MXJO0047; 
            if (codigoEstado==0) { 
               codigoEstado = 3200; 
               temperatura_txt.text = ""; 
               estado_txt.text = ""; 
               dtosEx_txt.text =""; 
            } else { 
               temperatura_txt.text = event.data.current.temperature+"º"; 
               estado_txt.text = xmlList.@value[codigoEstado]; 
               dtosEx_txt.text = "Viento: "+event.data.current.wind.direction+" "+event.data.current.wind.speed+" "+event.data.units.speed+"\n"+"Humedad: "+event.data.current.atmosphere.humidity+"%"+"\n"+"Visibilidad: "+event.data.current.atmosphere.visibility+" "+event.data.units.distance+"\n"+"Presión atmosférica: "+event.data.current.atmosphere.pressure+" "+event.data.units.pressure; 
               /* esttemp1_txt.text  = event.data.forecast[0].high+"º   "+ event.data.forecast[0].low+"º"; 
               esttemp2_txt.text  = event.data.forecast[1].high+"º   "+ event.data.forecast[1].low+"º";  */
            } 
            [Binding] var urlImagen:String = "imgactual/"+codigoEstado+".png"; 
         }
      ]]>
   
   </fx:Script>
   


Muchas gracias.

Por px87

Claber

141 de clabLevel

1 tutorial

Genero:Masculino  

firefox
Citar            
MensajeEscrito el 01 Jul 2010 10:53 pm
El this no es necesario, usa solo el nombre de la función

Jorge

Por solisarg

BOFH

13669 de clabLevel

4 tutoriales
5 articulos

Genero:Masculino   Bastard Operators From Hell Premio_Secretos

Argentina

firefox
Citar            
MensajeEscrito el 01 Jul 2010 10:57 pm
jaja muchas gracias jorge, pero revisando mas a fondo con la cabeza fria, me estoy dando cuenta que el problema no es solo el this, son mas partes del codigo q tienen problemas, al parecer el copy-paste y el pequeño reacomodo q le di no va a ser suciente aunado a q tal vez la api no sea compatible con flex 4 (aunque es actions script, lo se).

Saludos y gracias.

Por px87

Claber

141 de clabLevel

1 tutorial

Genero:Masculino  

firefox
Citar            
MensajeEscrito el 04 Jul 2010 12:50 am
Hola de nuevo, pues con la novedad de que he logrado mi cometido de hacer funcionar la aplicación yahoo weather API en Flex directamente.

Me tope con los siguientes problemas y dejo mis anotaciones:

1.- La aplicación no funciona con los tags de Flex 4
2.- Por la anterior causa tuve que "moldear" la aplicación en Flex 3 y luego pasarla (abrirla) en Flex 4
3.- La aplicación se corre en Flex 4 con el compilador de Flex 4 (no 3.5, ni moodo de compatibilidad)
4.- Para poder usarlo en Flex 4 uso un SWFLoader
5.- ¿Por qué usar la API directamente en Flex y no utilizar el swf de leobaraldi?
R = Porque no tengo casi nada de conocimiento en flash y creo que se le puede sacar más jugo a la API en flex ya
que (a mi parecer) la manipulación de componentes, información, etc. es más facil.

Bueno, sin más preambulos aquí les dejo lo que hice, si les gusta me dicen para subir el paque que utilicé:

No se asusten por tanto código, el XML hace que se vea bastan, disculpen si no usé una urlloader, un urlrequest y todo lo que se necesita para cargar un XML, pero no se por qué las funciones que utilicé nunca funcionaron.

Código :


Código Flex :

<?xml version="1.0" encoding="utf-8"?> 
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"  xmlns:yahoo="http://www.yahoo.com/astra/2006/mxml" 
    verticalAlign="top" paddingTop="2" creationComplete="init()" width="668" layout="absolute" height="200" backgroundAlpha="0.0" backgroundColor="#0090FF"> 
   <mx:Style source="weather.css"/> 
    
   <!-- Yahoo! Web Services we will be accessing --> 
   <!-- Web service de yahoo que permite la recepcion de datos del clima --> 
   <yahoo:WeatherService id="weatherService" weatherLoaded="weatherResultEventHandler(event)"  
      invalidLocationError="weatherErrorEventHandler(event)" xmlLoadingError="weatherErrorEventHandler(event)"/> 
    
   <mx:Script> 
      
<![CDATA[  
          
         //--------importación de los paquetes de la API de yahoo------ 
         import com.yahoo.webapis.weather.CurrentConditions; 
         import com.yahoo.webapis.weather.ForecastConditions; 
         import com.yahoo.webapis.weather.Weather; 
         import com.yahoo.webapis.weather.events.WeatherErrorEvent; 
         import com.yahoo.webapis.weather.events.WeatherResultEvent; 
         //--------importación de los paquetes de la API de yahoo------ 
          
         import mx.controls.Alert; 
         import flash.events.Event; 
         import flash.events.TimerEvent; 
       
          
         //------------ Inicio. Actualiza (recarga) los datos cada 600000 milisegundos (10 min.)---------- 
          
         private var timer:Timer = new Timer(600000, 1);  
          
         private function actualizacionclima():void  
         {  
            timer.addEventListener(TimerEvent.TIMER_COMPLETE, timerCompleteHandler);  
            timer.start();  
         }  
          
         private function timerCompleteHandler(event:TimerEvent):void  
         {  
 
                init(); 
 
         } 
         //------------ Fin. Actualiza los datos cada 600000 milisegundos (10 min.)---------- 
          
            
         //------------ Muestra la última hora en que se hizo la actualización--------------- 
         private function fechaact():void{ 
            var fecha:Date = new Date(); 
            actualizacion.text = "Última actualización: " + fecha.getDay().toString() + "/"  
               + fecha.getDate().toString() + "/"  
               + fecha.getFullYear().toString() + "  -  "  
               + fecha.getHours().toString()  
               + ":" + fecha.getMinutes().toString() + " Hrs (Hora local)";             
         } 
         //--------------------------------------------------------------------------------- 
          
//--------------- XML hecho por leobaraldi que tiene los estados del tiempo como un array, 
// solo baste con pasarle el código del estado del tiempo que se obtiene con "weath.current.code"  
       
//-------------------------------- Inicio XML ------------------------------------------------- 
          
    private var mixml:XML = 
     
   <ES> 
    <clima code="0" value="Tornado" /> 
    <clima code="1" value="Tormenta tropical" /> 
    <clima code="2" value="Huracan" /> 
    <clima code="3" value="Tormentas severas" /> 
    <clima code="4" value="Tormentas eléctricas" /> 
    <clima code="5" value="Mixtos de lluvia y nieve" /> 
    <clima code="6" value="Mixtos de lluvia y aguanieve" /> 
    <clima code="7" value="Mixto de nieve y aguanieve" /> 
    <clima code="8" value="Congelación llovizna" /> 
    <clima code="9" value="Llovizna" /> 
    <clima code="10" value="Lluvia helada" /> 
    <clima code="11" value="Chubascos" /> 
    <clima code="12" value="Chubascos" /> 
    <clima code="13" value="Nieve" /> 
    <clima code="14" value="Nieve, Chubascos" /> 
    <clima code="15" value="Nieve, ventoso" /> 
    <clima code="16" value="Nieve" /> 
    <clima code="17" value="Granizo" /> 
    <clima code="18" value="Aguanieve" /> 
    <clima code="19" value="Tormenta de tierra" /> 
    <clima code="20" value="Niebla" /> 
    <clima code="21" value="Haze" /> 
    <clima code="22" value="Humo" /> 
    <clima code="23" value="blustery" /> 
    <clima code="24" value="Viento" /> 
    <clima code="25" value="Frío" /> 
    <clima code="26" value="Nublado" /> 
    <clima code="27" value="Chubascos por la noche" /> 
    <clima code="28" value="Día parcialmente nublado" /> 
    <clima code="29" value="Noche Parcialmente nublado" /> 
    <clima code="30" value="Día Parcialmente nublado" /> 
    <clima code="31" value="Noche Despejada" /> 
    <clima code="32" value="Soleado" /> 
    <clima code="33" value="Noche despejada" /> 
    <clima code="34" value="Día despejado" /> 
    <clima code="35" value="mixtos de lluvia y granizo" /> 
    <clima code="36" value="Caluroso" /> 
    <clima code="37" value="Tormentas aisladas" /> 
    <clima code="38" value="Tormentas aisladas" /> 
    <clima code="39" value="Tormentas aisladas" /> 
    <clima code="40" value="Chaparrones" /> 
    <clima code="41" value="Nieve" /> 
    <clima code="42" value="Tormenta de nieve dispersos" /> 
    <clima code="43" value="Nieve" /> 
    <clima code="44" value="Parcialmente nublado" /> 
    <clima code="45" value="Tormentas" /> 
    <clima code="46" value="snow showers" /> 
    <clima code="47" value="Tormentas aisladas" /> 
    <clima code="3200" value="Sin datos" /> 
    </ES> 
    ;// fin var mixml 
          
          
          
//-------------------------------- Fin XML ------------------------------------------------- 
          
         //Objeto de la clase Weather 
         private var weath:Weather; 
             
 
         //----- En caso de exista algún error en la carga de los datos ------ 
         private function weatherErrorEventHandler(ev:WeatherErrorEvent):void{ 
            Alert.show("Error al cargar los" + "\n" + "datos del clima", "Error");  
         } 
          
         //----- Carga exitosa de los datos ------ 
         private function weatherResultEventHandler(ev:WeatherResultEvent):void{ 
            //Los datos recibidos por medio del evento 'WeatherResultEvent'  
            //se guardan en el objeto anteriormente creado. 
             
            weath = ev.data as Weather; 
             
            // Variable para el código del estado del clima 
            var codigo:Number = weath.current.code; 
 
            //Clima actual              
            img.load("../imgsclima/" + codigo + ".png");                                //Imagenes obtenidas del paquete de leobaraldi                                                                   
            temp.text = weath.current.temperature.toString() + " °C";                   // Temperatura actual 
            infotemp.text =  
            "Sensación térmica: " +  weath.current.wind.chill.toString() + " °C" + "\n" // Sensación termina 
            + "Humedad: " + weath.current.atmosphere.humidity.toString()                // Humedad 
            + "%" + "\n" + "Visibilidad: "  
            + weath.current.atmosphere.visibility.toString() + " Km" + "\n";            // Visibilidad 
            estactual.text = mixml..@value[codigo];                                     // Estado actual (En español, gracial al XML antes mencionado) 
            
         } 
          
         //Inicializa la recpecion de datos de clima por medio del método 
         //weatherService.getWeather(lugar, "c") 
         //donde "lugar" es el código del lugar de donde queremos obtener los datos del clima 
         // y "c" son la unidades en que queremos recibir el clima ´c´ para celsius y 'f' para farenheit 
         private function init():void{ 
            var lugar:String = "MXJO0047"; 
            weatherService.getWeather(lugar, "c"); 
            actualizacionclima(); 
            fechaact(); 
         } 
          
       
]]>
 
   </mx:Script> 
    
   <!-- Y solo resta usar los datos como mejor nos convenga --> 
   <mx:Image x="35" y="50" width="74" height="74" id="img"/> 
   <mx:Label x="127" y="45" text="temp" id="temp" fontSize="48" fontWeight="bold" fontFamily="Comic Sans MS" color="#FFFFFF" textAlign="right" alpha="1.0"/> 
   <mx:Label x="35" y="127" text="estactual" fontSize="20" id="estactual" fontStyle="normal" fontWeight="bold" color="#FFFFFF" fontFamily="Comic Sans MS" textDecoration="none"/> 
   <mx:Text x="347" text="tempinfo" width="310" height="131" id="infotemp" fontSize="20" fontFamily="Comic Sans MS" color="#FFFFFF" alpha="1.0" verticalCenter="14"/> 
   <mx:Label x="127" y="1" text="Puerto Vallarta, Jal." fontSize="25" fontFamily="Comic Sans MS" color="#FFFFFF" fontStyle="normal" id="lugar" width="244"/> 
   <mx:Label fontSize="13" fontFamily="Comic Sans MS" color="#FFFFFF" id="actualizacion" width="403" verticalCenter="87" horizontalCenter="0" text="actualizacion"/> 
</mx:Application> 





Aquí una imágen del resultado:



Saludos.

Por px87

Claber

141 de clabLevel

1 tutorial

Genero:Masculino  

firefox
Citar            
MensajeEscrito el 09 Sep 2010 05:41 am
Quedo re lindo! felicitaciones! :wink:

Por leobaraldi

351 de clabLevel

3 tutoriales

 

firefox
Citar            
MensajeEscrito el 09 Sep 2010 11:25 pm
Muchas gracias, un honor q tu me digas eso.

Saludos.

Por px87

Claber

141 de clabLevel

1 tutorial

Genero:Masculino  

firefox

 

Cristalab BabyBlue v4 + V4 © 2011 Cristalab
Powered by ClabEngines v4, HTML5, love and ponies.