天氣預報API簡單實現

本人小白,以爲好玩,就註冊了一個博客。一時也不知道寫些什麼,就把昨天作的一個簡單的網頁天氣預報寫一下吧,但願對各位看官有所幫助。php

運行環境:php+mysql+WIN/Linux,框架什麼的都無所謂了吧。css

我的理解:html

 

很簡單的,經過API獲取到天氣的Json數據,而後後臺傳給前端展現,css渲染。前端

首先,獲取API的數據:mysql

我這裏找的是一個免費的天氣預報API,方便實用,用的人也多: http://apistore.baidu.com/apiworks/servicedetail/112.html ajax

我把相關的方法給寫在一個php文件裏,方便使用:weather.phpsql

 1 function weather_excu_curl($url){
 2     $ch = curl_init();
 3     $header = array(
 4         'apikey:你本身的apikey',
 5     );
 6     // 添加apikey到header
 7     curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
 8     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 9     // 執行HTTP請求
10     curl_setopt($ch, CURLOPT_URL, $url);
11     $res = curl_exec($ch);
12     return $res;
13 }
14 
15 //根據城市名稱-- type == 0 獲取城市代碼,!=0 獲取天氣總體信息
16 function get_cityCode($cityname,$type){
17     //獲取城市代碼
18     $url_city = 'http://apis.baidu.com/apistore/weatherservice/cityname?cityname='.$cityname;
19     $res = weather_excu_curl($url_city);
20     $res = json_decode($res);
21     $errnum = $res->errNum;
22     if($type == 0) {
23         //當地基本天氣信息
24         if ($errnum != -1) {
25             return $res->retData->citycode;
26         } else {
27             return null;
28         }
29     }else{
30         return $res;
31     }
32 }
33 //帶歷史7天和將來4天--天氣查詢
34 function get_recent_weather($citycode){
35     if($citycode) {
36         $url = 'http://apis.baidu.com/apistore/weatherservice/recentweathers?cityid=' . $citycode;
37         return weather_excu_curl($url);
38     }else{
39         return null;
40     }
41 }
而後,把獲得的數據放到前端就能夠了,我這裏使用ajax進行異步加載的方式:
js文件
 1 function getWeather(){
 2 //dealid 傳遞給後臺處理的參數
 3     var dealid = $("#dealid").val();
 4     $.ajax({
 5         url:"你的後臺處理地址",
 6         dataType: "json",
 7         async:false,
 8         data:{"dealid":dealid},
 9         type:"POST",
10         success:function(msg){
11             var container = $("#weather_info");
12             if(msg['status']!=0) {
13                 var data = msg['data']['retData'];
14                 console.log(data);
15                 $("#weather_nav .weather_city").html(data['city']);
16                 if(data.today){
17                     var history = data.history;
18                     var forecast = data.forecast;
19                     //data  today weather
20                     var todayContent = data.today.index;
21                     var todayHtml = "";
22                     var todayLength = todayContent.length;
23                     for (var i=0;i<todayLength;i++){
24                         todayHtml += "<div class='"+todayContent[i]['code']+"'>" +
25                             "<p>"+todayContent[i]['name']+" "+todayContent[i]['index']+"</p>" +
26                             "<p>"+todayContent[i]['details']+"</p>" +
27                             "</div>";
28                     }
29                     container.append("<div class='weather_today'>" +
30                         "<ul>" +
31                         "<li>溫度 :"+data.today.curTemp+" / "+data.today.type+"</li>" +
32                         "<li>時間 :"+data.today.date+" / "+data.today.week+"</li>" +
33                         "<li>風力 :"+data.today.fengli+"</li>" +
34                         "<li>風向 :"+data.today.fengxiang+"</li>" +
35                         "<li>最高溫 :"+data.today.hightemp+"</li>" +
36                         "<li>最低溫 :"+data.today.lowtemp+"</li>" +
37                         "<li>PM值 :"+data.today.aqi+"</li>" +
38                         "<li>"+todayHtml+"</li>" +
39                         "</ul>" +
40                         "</div>");
41                     //history weather
42                     var historyLength = history.length;
43                     var historyHtml = "";
44                     for(var i=0; i < historyLength;i++){
45                         historyHtml +="<li><p>天氣 :"+history[i]['type']+"</p>" +
46                             "<p>時間 :"+history[i]['date']+" / "+history[i]['week']+"</p>" +
47                             "<p>風力 :"+history[i]['fengli']+"</p>"+
48                             "<p>風向 :"+history[i]['fengxiang']+"</p>"+
49                             "<p>最高溫 :"+history[i]['hightemp']+"</p>"+
50                             "<p>最低溫 :"+history[i]['lowtemp']+"</p>"+
51                             "<p>PM值 :"+history[i]['aqi']+"</p></li>";
52                     }
53                     container.append("<div class='weather_history'><ul>"+historyHtml+"</ul></div>");
54                     //forecast weather
55                     var forecastLength = forecast.length;
56                     var forecastHtml = "";
57                     for(var i=0; i < forecastLength;i++){
58                         forecastHtml +="<li><p>天氣 :"+forecast[i]['type']+"</p>" +
59                             "<p>時間 :"+forecast[i]['date']+" / "+forecast[i]['week']+"</p>" +
60                             "<p>風力 :"+forecast[i]['fengli']+"</p>"+
61                             "<p>風向 :"+forecast[i]['fengxiang']+"</p>"+
62                             "<p>最高溫 :"+forecast[i]['hightemp']+"</p>"+
63                             "<p>最低溫 :"+forecast[i]['lowtemp']+"</p></li>";
64                     }
65                     container.append("<div class='weather_forecast'><ul>"+forecastHtml+"</ul></div>");
66                 }
67             }else {
68                 container.append(msg.content);
69                 $("#weather_nav").css("display","none");
70             }
71         },
72         error:function(){
73             console.log("出錯");
74         }
75     });
76 }

後臺處理代碼(要include 以前寫的 weather.php):json

 1 require '/weather.php';
 2 class weatherModule extends BaseModule
 3 {
 4     public function weather(){
 5         $dealid = $_POST['dealid'];
 6         $deal = mysql查詢到相關的數據;
 7         //city
 8         $cityCode = get_cityCode($deal['city'],0);
 9         if($cityCode) {
10             $res = get_recent_weather($cityCode);
11             echo json_encode(array("status"=>1,"data"=>json_decode($res)));
12         }else{
13             //province
14             $citycode0 = get_cityCode($deal['province']);
15             if($citycode0){
16                 $res0 = get_recent_weather($citycode0,0);
17                 echo json_encode(array("status"=>2,"data"=>json_decode($res0)));
18             }else{
19                 echo json_encode(array("status"=>0,"content"=>"沒有查到該地區天氣數據"));
20             }
21         }
22     }
23 }

最後頁面展現html部分代碼:api

1 <input id="dealid" type="text" placeholder="輸入賽事id 查詢最近城市天氣" style="width: 400px;">
2 <input type="submit" onclick="getWeather()">
3     <div id="weather_info">
4                 <!--這裏是Js異步加載的天氣數據-->
5     </div>
6 </body>

代碼寫完了,我發現這個天氣預報的樣子和本身想象的簡直雲泥之別:app

 

剩下的,就交給美工和前端吧。

相關文章
相關標籤/搜索