yii2.0-天气预报小部件

作者:谢高升 发布:2017-10-11 浏览:2489次

在widgets目录新建weather目录

创建WeatherWidget.php

<?php
namespace frontend\widgets\weather;

use yii\base\Widget;

/**
 *
 * @author xiaoxie
 *        
 */
class WeatherWidget extends Widget
{

    public function postUrl($url, $data = [])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $handles = curl_exec($ch);
        curl_close($ch);
        return $handles;
    }

    public function getUrl($url, $data = [])
    {
        $ch = curl_init();
        // 设置选项,包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        // 执行并获取HTML文档内容
        $output = curl_exec($ch);
        // 释放curl句柄
        curl_close($ch);
        return $output;
    }

    /**
     * 获取经纬度
     * 
     * @return mixed
     */
    public function getPoint()
    {
        $latlon = $this->postUrl('http://api.map.baidu.com/location/ip?ak=CXtGNbmUioe3pfZ0yvnsNDjaYj63vQ8C&coor=bd09ll');
        $latlonarr = json_decode($latlon, true);
        $point = $latlonarr['content']['point'];
        return $point;
    }

    /**
     * 根据经纬度获取城市
     * 
     * @param unknown $point
     * @return mixed
     */
    public function getCity()
    {
        $ip = $_SERVER["REMOTE_ADDR"];
        $city = $this->getUrl('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=' . $ip);
        
        $cityarr = json_decode($city, true);
        // 城市名称
        $cityname = $cityarr['city'];
        return $cityname;
    }

    /**
     * 获取天气预报接口
     * 
     * @return string|number[]
     */
    public function getWeatherinfo()
    {
        $cityname = $this->getCity();
        
        // print_r($cityname);exit;
        $data = $this->getUrl('http://www.sojson.com/open/api/weather/json.shtml?city=' . $cityname);
        $weatherdata = json_decode($data, true);
        $weatherarr = [];
        if ($weatherdata['status'] == 200) {
            foreach ($weatherdata['data']['forecast'] as $key => $value) {
                
                $weatherarr[$key]['date'] = $value['date'];
                $weatherarr[$key]['high'] = $value['high'];
                $weatherarr[$key]['low'] = $value['low'];
                $weatherarr[$key]['fx'] = $value['fx'];
                $weatherarr[$key]['fl'] = $value['fl'];
                $weatherarr[$key]['type'] = $value['type'];
                $weatherarr[$key]['notice'] = $value['notice'];
                $weatherarr[$key]['icon'] =$value['icon'];
               
            }
        } else {
            $weatherarr['status'] = 500;
            $weatherarr[0]['date'] = date('Y-m-d');
            $weatherarr[0]['icon'] = '';
            $weatherarr[0]['high'] = '';
            $weatherarr[0]['low'] = '';
            $weatherarr[0]['fx'] = '';
            $weatherarr[0]['fl'] = '';
            $weatherarr[0]['type'] = '正在掐指计算';
            $weatherarr[0]['notice'] = '正在加载中';
        }
        return $weatherarr;
    }

    /**
     *
     * {@inheritdoc}
     * @see \yii\base\Widget::run()
     */
    public function run()
    {
        $point = $this->getPoint();
        
        $cityname = $this->getCity($point);
        $weatherarr = $this->getWeatherinfo();
        $i = 0;
        foreach ($weatherarr as $key => $value) {
            if (substr($value['date'], 0, 2) == date('d')) {
                $i = $key;
            }
        }
        
        return $this->render('index', [
            'data' => $weatherarr,
            'city' => $cityname,
            'i' => $i
        ]);
    }
}

创建一个视图文件index.php

<div class="fright">
	<div class="module weather_detail">
		<div id="weatherInfo" style="">
			<div class="btitle">
				<h2><?=$city ?>市天气预报</h2>
			</div>
			<div class="bmeta">
			<?php if(Yii::$app->request->get('type') == 'more'):?>
					<div class="row">
					<div class="col-lg-12">
							<?php foreach ($data as $list):?>
								<div class="stitle"><?=$list['date'] ?>&nbsp;
									<span style='color: #5BC0DE'><?=$list['type'] ?></span> <span
								style='font-family: cursive;'>&nbsp;<?=$list['fx'] ?></span>
						</div>
						<div class="panel"></div>
							<?php endforeach;?>
						</div>
				</div>
			<?php else:?>
				<div class="days2">
					<div class="row">
						<div class="stitle">
							<span style='padding-left: 5%'>今天</span>&nbsp;&nbsp;<?=$data[$i]['date'] ?></div>
						<div class="panel"></div>
						<div class="col-lg-8" style='padding-left: 20%'>
							<div class="icon">
								<span id="dayIcon" class="<?=$data[$i]['icon'] ?>"></span>
							</div>
							<div class="phrase">
								<em>天气:</em><span id="dayTxt"><?=$data[$i]['type'] ?></span>
							</div>
						</div>

					</div>
					<div class='panel'></div>
					<div class="row" style='padding-left: 20%'>
						<div class="temperature">
							<span class="low" id="lowT"><?=$data[$i]['low'] ?></span>~<span
								class="high" id="highT"><?=$data[$i]['high'] ?></span>
						</div>


						<div class="panel" style='padding-top: 5px'>风向:<?=$data[$i]['fx'] ?></div>
						<div class="panel" style='padding-top: 5px'>
							<span style='color: red'>温馨提醒:<?=$data[$i]['notice'] ?></span>
						</div>
						<a class="layer today-layer" href="/today-58362.htm"
							target="_blank" id="todayHref"></a>
					</div>
				</div>
				<div class="panel"></div>
				<?php endif;?>
				<div class="row">
					<div class="col-lg-12" style='padding-left: 7%'>
						<a href="<?=Url::to(['site/index','type'=>'more']) ?>"><div
								class="btn-more btn btn-info btn-block btn-post">查看7日天气预报</div></a>
					</div>

				</div>

			</div>
		</div>
	</div>
</div>




标签: widges