jQ、Yahoo API和HTML 5开发天气预报应用

开发 前端
使用Geolocation取得用户的地理位置信息,然后,使用yahoo的 PlaceFinder API,来通过经纬度来找到具体地点,例如,城市或者国家。其中包括了woeid,这个用来在天气预报应用中找到国家。

使用jQuery,Yahoo API和HTML5的geolocation来开发一个天气预报web应用

在线演示  本地下载

今天我们介绍来自tutorialzine的一个HTML5/jQuery/Yahoo API的开发教程,在这篇文章中我们将介绍如何使用HTML5的Geolocation,jQuery和YahooAPI来开发一个天气预报web应用。 如果你不熟悉HTML5的Geolocation(地理位置服务),请参考我们的HTML5教程: HTML5 Geolocation

首先你需要得到Yahoo API的API key,你可以通过如下地址取得对应的API key:https://developer.apps.yahoo.com/dashboard/createKey.html

以上创建过程中会要求你输入相关应用地址等信息。创建成功后,你可以得到APPID。

主要思路

在这个教程中,我们主要思路如下:

使用Geolocation取得用户的地理位置信息

然后,使用yahoo的 PlaceFinder API,来通过经纬度来找到具体地点,例如,城市或者国家。其中包括了woeid,这个用来在天气预报应用中找到国家。

最后,我们将调用yahoo的Weather API来取得天气。

web应用代码

#p#

HTML

  1. <!DOCTYPE html> 
  2. <html> 
  3.     <head> 
  4.         <meta charset="gbk" /> 
  5.         <title>Weather Forecast with jQuery &amp; Yahoo APIs</title> 
  6.           
  7.         <!-- The stylesheet --> 
  8.         <link rel="stylesheet" href="assets/css/styles.css" /> 
  9.           
  10.         <!-- Google Fonts --> 
  11.         <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Playball|Open+Sans+Condensed:300,700" /> 
  12.           
  13.         <!--[if lt IE 9]> 
  14.           <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> 
  15.         <![endif]--> 
  16.     </head> 
  17.       
  18.     <body> 
  19.  
  20.         <header> 
  21.             <h1>Weather Forecast</h1> 
  22.         </header> 
  23.           
  24.         <div id="weather"> 
  25.  
  26.             <ul id="scroller"> 
  27.                 <!-- The forecast items will go here --> 
  28.             </ul> 
  29.               
  30.             <a href="#" class="arrow previous">Previous</a> 
  31.             <a href="#" class="arrow next">Next</a> 
  32.               
  33.         </div> 
  34.           
  35.         <p class="location"></p> 
  36.           
  37.         <div id="clouds"></div> 
  38.           
  39.         <footer> 
  40.             <h2><i>Tutorial:</i> Weather Forecast with jQuery &amp; Yahoo APIs</h2> 
  41.             <a class="tzine" href="http://tutorialzine.com/2012/05/weather-forecast-geolocation-jquery/">Head on to <i>Tutorial<b>zine</b></i> to download this example</a> 
  42.         </footer> 
  43.           
  44.         <!-- JavaScript includes - jQuery, turn.js and our own script.js --> 
  45.         <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script> 
  46.         <script src="assets/js/script.js" charset="utf-8"></script> 
  47.           
  48.     </body> 
  49. </html> 

#p#

Javascript

  1. $(function(){  
  2.       
  3.     /* Configuration */ 
  4.       
  5.     var APPID = 'fa2pT26k';        // Your Yahoo APP id  
  6.     var DEG = 'c';        // c for celsius, f for fahrenheit  
  7.       
  8.     // Mapping the weather codes returned by Yahoo's API  
  9.     // to the correct icons in the img/icons folder  
  10.       
  11.     var weatherIconMap = [  
  12.         'storm''storm''storm''lightning''lightning''snow''hail''hail',  
  13.         'drizzle''drizzle''rain''rain''rain''snow''snow''snow''snow',  
  14.         'hail''hail''fog''fog''fog''fog''wind''wind''snowflake',  
  15.         'cloud''cloud_moon''cloud_sun''cloud_moon''cloud_sun''moon''sun',  
  16.         'moon''sun''hail''sun''lightning''lightning''lightning''rain',  
  17.         'snowflake''snowflake''snowflake''cloud''rain''snow''lightning' 
  18.     ];  
  19.       
  20.     var weatherDiv = $('#weather'),  
  21.         scroller = $('#scroller'),  
  22.         location = $('p.location');  
  23.       
  24.     // Does this browser support geolocation?  
  25.     if (navigator.geolocation) {  
  26.         navigator.geolocation.getCurrentPosition(locationSuccess, locationError);  
  27.     }  
  28.     else{  
  29.         showError("Your browser does not support Geolocation!");  
  30.     }  
  31.       
  32.     // Get user's location, and use Yahoo's PlaceFinder API  
  33.     // to get the location name, woeid and weather forecast  
  34.       
  35.     function locationSuccess(position) {  
  36.         var lat = position.coords.latitude;  
  37.         var lon = position.coords.longitude;  
  38.  
  39.         // Yahoo's PlaceFinder API http://developer.yahoo.com/geo/placefinder/  
  40.         // We are passing the R gflag for reverse geocoding (coordinates to place name)  
  41.         var geoAPI = 'http://where.yahooapis.com/geocode?location='+lat+','+lon+'&flags=J&gflags=R&appid='+APPID;  
  42.           
  43.         // Forming the query for Yahoo's weather forecasting API with YQL  
  44.         // http://developer.yahoo.com/weather/  
  45.           
  46.         var wsql = 'select * from weather.forecast where woeid=WID and u="'+DEG+'"',  
  47.             weatherYQL = 'http://query.yahooapis.com/v1/public/yql?q='+encodeURIComponent(wsql)+'&format=json&callback=?',  
  48.             code, city, results, woeid;  
  49.           
  50.         if (window.console && window.console.info){  
  51.             console.info("Coordinates: %f %f", lat, lon);  
  52.         }  
  53.           
  54.         // Issue a cross-domain AJAX request (CORS) to the GEO service.  
  55.         // Not supported in Opera and IE.  
  56.         $.getJSON(geoAPI, function(r){  
  57.              
  58.             if(r.ResultSet.Found == 1){  
  59.                   
  60.                 results = r.ResultSet.Results;  
  61.                 city = results[0].city;  
  62.                 code = results[0].statecode || results[0].countrycode;  
  63.           
  64.                 // This is the city identifier for the weather API  
  65.                 woeid = results[0].woeid;  
  66.       
  67.                 // Make a weather API request:  
  68.                 $.getJSON(weatherYQL.replace('WID',woeid), function(r){  
  69.                       
  70.                     if(r.query && r.query.count == 1){  
  71.                           
  72.                         // Create the weather items in the #scroller UL  
  73.                           
  74.                         var item = r.query.results.channel.item.condition;  
  75.                           
  76.                         if(!item){  
  77.                             showError("We can't find weather information about your city!");  
  78.                             if (window.console && window.console.info){  
  79.                                 console.info("%s, %s; woeid: %d", city, code, woeid);  
  80.                             }  
  81.                               
  82.                             return false;  
  83.                         }  
  84.                           
  85.                         addWeather(item.code, "Now", item.text + ' <b>'+item.temp+'°'+DEG+'</b>');  
  86.                           
  87.                         for (var i=0;i<2;i++){  
  88.                             item = r.query.results.channel.item.forecast[i];  
  89.                             addWeather(  
  90.                                 item.code,   
  91.                                 item.day +' <b>'+item.date.replace('\d+$','')+'</b>',  
  92.                                 item.text + ' <b>'+item.low+'°'+DEG+' / '+item.high+'°'+DEG+'</b>' 
  93.                             );  
  94.                         }  
  95.                           
  96.                         // Add the location to the page  
  97.                         location.html(city+', <b>'+code+'</b>');  
  98.                           
  99.                         weatherDiv.addClass('loaded');  
  100.                           
  101.                         // Set the slider to the first slide  
  102.                         showSlide(0);  
  103.                      
  104.                     }  
  105.                     else {  
  106.                         showError("Error retrieving weather data!");  
  107.                     }  
  108.                 });  
  109.           
  110.             }  
  111.               
  112.         }).error(function(){  
  113.             showError("Your browser does not support CORS requests!");  
  114.         });  
  115.          
  116.     }  
  117.       
  118.     function addWeather(code, day, condition){  
  119.           
  120.         var markup = '<li>'+  
  121.             '<img src="assets/img/icons/'+ weatherIconMap[code] +'.png" />'+  
  122.             ' <p class="day">'+ day +'</p> <p class="cond">'+ condition +  
  123.             '</p></li>';  
  124.           
  125.         scroller.append(markup);  
  126.     }  
  127.       
  128.     /* Handling the previous / next arrows */ 
  129.       
  130.     var currentSlide = 0;  
  131.     weatherDiv.find('a.previous').click(function(e){  
  132.         e.preventDefault();  
  133.         showSlide(currentSlide-1);  
  134.     });  
  135.       
  136.     weatherDiv.find('a.next').click(function(e){  
  137.         e.preventDefault();  
  138.         showSlide(currentSlide+1);  
  139.     });  
  140.       
  141.       
  142.     function showSlide(i){  
  143.         var items = scroller.find('li');  
  144.           
  145.         if (i >= items.length || i < 0 || scroller.is(':animated')){  
  146.             return false;  
  147.         }  
  148.           
  149.         weatherDiv.removeClass('first last');  
  150.           
  151.         if(i == 0){  
  152.             weatherDiv.addClass('first');  
  153.         }  
  154.         else if (i == items.length-1){  
  155.             weatherDiv.addClass('last');  
  156.         }  
  157.           
  158.         scroller.animate({left:(-i*100)+'%'}, function(){  
  159.             currentSlide = i;  
  160.         });  
  161.     }  
  162.       
  163.     /* Error handling functions */ 
  164.       
  165.     function locationError(error){  
  166.         switch(error.code) {  
  167.             case error.TIMEOUT:  
  168.                 showError("A timeout occured! Please try again!");  
  169.                 break;  
  170.             case error.POSITION_UNAVAILABLE:  
  171.                 showError('We can\'t detect your location. Sorry!');  
  172.                 break;  
  173.             case error.PERMISSION_DENIED:  
  174.                 showError('Please allow geolocation access for this to work.');  
  175.                 break;  
  176.             case error.UNKNOWN_ERROR:  
  177.                 showError('An unknown error occured!');  
  178.                 break;  
  179.         }  
  180.           
  181.     }  
  182.       
  183.     function showError(msg){  
  184.         weatherDiv.addClass('error').html(msg);  
  185.     }  
  186.  
  187. }); 

搞定!具体演示请参考在线Demo,希望大家喜欢这个web应用!

 

原文链接:http://www.cnblogs.com/gbin1/archive/2012/06/14/2549525.html

【编辑推荐】

  1. jQuery 烟花效果(运动相关)
  2. 到处都是jQuery选择器的年代
  3. jQuery:让文盲秀网页
  4. 新版jQuery div弹出层的ajax登录
  5. jQuery图片延迟加载技术的应用
责任编辑:张伟 来源: gbin1的博客
相关推荐

2016-03-14 10:29:38

天气预报各类工具源码

2013-03-26 13:20:27

Android天气预报

2009-07-07 09:25:08

Linux开发FOSS开发项目

2022-02-21 11:02:54

5G通信网络天气预报

2013-04-10 17:59:50

微信公众平台接口开发

2010-08-13 10:56:58

FlexWebservice

2017-08-01 10:10:32

人工智能智能天气预报

2013-09-09 10:52:10

2012-03-13 16:45:09

超级计算机沃森Deep Thunde

2018-01-29 11:25:37

LinuxASCII 字符天气预报

2020-02-11 20:00:29

开源开源工具天气预报

2009-12-02 15:45:04

PHP抓取天气预报

2012-07-16 13:36:54

交换机数据中心核心交换机气象卫星

2023-10-27 16:15:35

鸿蒙天气服务功能

2020-01-16 15:13:40

AI预测天气预报

2009-04-17 17:11:18

ASP.NET新浪天气

2015-10-19 17:16:10

天气预报命令行Linux

2009-08-26 16:59:44

2019-10-25 19:42:41

华为

2022-02-21 15:07:48

气象学人工智能AI
点赞
收藏

51CTO技术栈公众号