JavaScript >> Javascript 文檔 >  >> jQuery

如何使用 Geolocation 和 Yahoo 的 API 構建一個簡單的天氣 webapp

今天我們將使用 HTML5 地理定位 API 向用戶展示個性化的天氣預報。使用 jQuery,我們將向雅虎的兩個流行 API 發出 AJAX 請求,以獲取額外的地理信息和天氣預報。這個例子還利用了精彩的climacon圖標集。

獲取應用程序密鑰

Yahoo 提供了大量有用的 API,可供開發人員免費使用。要求是您通過他們的開發人員儀表板註冊您的應用程序。註冊簡單明了,因此您會獲得一個應用程序 ID(在您的應用程序標題下查找它)。在本教程的後面部分您將需要它,但首先讓我們看看一切如何協同工作。

理念

為了顯示我們的天氣預報,我們需要執行以下操作:

  • 首先我們將使用 Geolocation API 現代瀏覽器支持。 API 將提示用戶授權位置訪問並返回一組 GPS 坐標;
  • 接下來,我們將向 Yahoo 的 PlaceFinder API 發出請求,傳遞上述坐標。這將為我們提供城市和國家/地區的名稱,以及 woeid - 用於在天氣預報中識別城市的特殊 ID;
  • 最後,我們將使用該 woeid 向 Yahoo 的 Weather API 發出請求。這將為我們提供當前的天氣狀況,以及當前剩餘時間和第二天的預報。

偉大的!我們現在已經為 HTML 做好了準備。

HTML

我們將從一個空白的 HTML5 文檔開始,並將對樣式表的引用添加到 head 部分,以及來自 Google 的 Webfonts 庫的兩種字體。在正文中,我們將為天氣預報滑塊添加一個 h1 標題和標記。

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Weather Forecast with jQuery &amp; Yahoo APIs | Tutorialzine Demo</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>

        <!-- 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"></script>

    </body>
</html>

在結束 body 標記之前,我們添加了最新版本的 jQuery 和我們的 script.js 文件,我們將在以下部分討論。

JavaScript

第一步是在/assets/js/script.js中定義兩個配置變量 :

var APPID = '';   // Your Yahoo Application ID
var DEG = 'c';  // c for celsius, f for fahrenheit

正如您稍後將看到的,這些作為參數與位置和天氣 API 的 AJAX 請求一起傳遞。

按照想法部分的大綱,我們現在應該研究使用 HTML5 Geolocation API 獲取一組 GPS 坐標。所有新瀏覽器都支持此 API,包括 IE9 和移動設備。要使用它,我們需要測試全局導航器對像是否有 geolocation 財產。如果是,我們調用它的 getCurrentPosition 方法傳遞成功和失敗的兩個事件處理函數。這是來自 script.js 的相關代碼 這樣做:

// Does this browser support geolocation?
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(locationSuccess, locationError);
}
else{
    showError("Your browser does not support Geolocation!");
}

function locationSuccess(position) {
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;

    // We will make further requests to Yahoo's APIs here
}

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);
}

locationSuccess 函數是我們稍後將向 Yahoo 的 API 發出請求的地方。 locationError 函數被傳遞一個帶有錯誤條件的具體原因的錯誤對象。我們將使用 showError 幫助函數在屏幕上顯示錯誤消息。

locationSuccess的完整版 如下:

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;

    // 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 (it is JSONP, so CORS is not an issue):
            $.getJSON(weatherYQL.replace('WID',woeid), function(r){

                if(r.query.count == 1){

                    // Create the weather items in the #scroller UL

                    var item = r.query.results.channel.item.condition;
                    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!");
    });

}

PlaceFinder API 以純 JSON 形式返回其結果。但由於它位於不同的域中,只有支持 CORS(跨源資源共享)的瀏覽器才能檢索它。大多數支持地理定位的主流瀏覽器也支持 CORS,除了 IE9 和 Opera,這意味著這個例子在那裡不起作用。

另一件需要考慮的事情是,天氣 API 只返回兩天的預報,這在一定程度上限制了我們 Web 應用的實用性,但不幸的是,沒有辦法繞過它。

檢索天氣數據後,我們調用 addWeather 函數,它在 #scroller 中創建一個新的 LI 項 無序列表。

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');

        // Exit if the requested item does not exist,
        // or the scroller is currently being animated
        if (i >= items.length || i < 0 || scroller.is(':animated')){
            return false;
        }

        // The first/last classes hide the left/right arrow with CSS
        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;
        });
    }

有了這個我們簡單的天氣網絡應用程序就完成了! 您可以在 /assets/js/script.js 中一起查看所有內容 .我們不會在這裡討論樣式,但您可以閱讀 /assets/css/styles.css 自己。

完成!

在此示例中,您學習瞭如何使用 HTML5 地理定位和 Yahoo 的 Weather 和 Places API 來呈現位置感知天氣預報。它適用於大多數現代網絡瀏覽器和移動設備。


Tutorial JavaScript 教程
  1. 在自定義(非本機)組件上使用 v-tooltip

  2. 又翻了一堵牆

  3. 終於重建了我的個人網站

  4. 前端開發:從零到英雄

  5. 使用 freeCodeCamp 挑戰解釋 JavaScript 中的遞歸

  6. 使用 JavaScript 獲取位數

  7. 如何在 Angular 14 應用程序中使用 NgIf、Else、然後

  1. 將二進制轉換為十進制

  2. 以快速簡單的方式測試全局 npm 包

  3. 純組件、接口和邏輯掛鉤。

  4. 2016 年 NodeSource 的 9 篇最佳文章

  5. 使用 Array.includes() 條件更易讀

  6. 有效使用 Array.prototype 方法。

  7. React 中的依賴注入

  1. 解壓縮/解壓縮 JavaScript 的工具

  2. 找出哪些 JavaScript 變量洩漏到全局範圍內

  3. Search Dragon - 我的搜索引擎網絡應用🔍🐲

  4. 使用 Typeform、Clearbit、Airtable 和標準庫在 5 分鐘內構建潛在客戶生成器