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

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

#p#

Javascript

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

2010-08-13 10:56:58

FlexWebservice

2013-04-10 17:59:50

微信公众平台接口开发

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

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

2020-01-16 15:13:40

AI预测天气预报

2009-04-17 17:11:18

ASP.NET新浪天气

2023-10-27 16:15:35

鸿蒙天气服务功能

2015-10-19 17:16:10

天气预报命令行Linux

2009-08-26 16:59:44

Web Service

2019-10-25 19:42:41

华为

2022-02-21 15:07:48

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

51CTO技术栈公众号