PHP调用全国天气预报数据接口查询天气示例(2)

三、根据用户的IP地址请求对应的天气预报

通过用户的IP地址获取用户所在地的天气预报,由于IP地址解析可能会有误差,所以有时定位到的城市不一定是用户实际的所在地。

$ipWeatherResult = $weather->getWeatherByIP('58.215.154.128');
if($ipWeatherResult['error_code'] == 0){  //以下可根据实际业务需求,自行改写
  //////////////////////////////////////////////////////////////////////
  $data = $ipWeatherResult['result'];
  echo "=======当前城市=======<br>";
  echo $data['today']['city'];
  echo "<br><br>";
  echo "=======当前天气实况=======<br>";
  echo "温度:".$data['sk']['temp']."  ";
  echo "风向:".$data['sk']['wind_direction']."  (".$data['sk']['wind_strength'].")";
  echo "湿度:".$data['sk']['humidity']."  ";
  echo "<br><br>";
  echo "=======未来几天天气预报=======<br>";
  foreach($data['future'] as $wkey =>$f){
    echo "日期:".$f['date']." ".$f['week']." ".$f['weather']." ".$f['temperature']."<br>";
  }
  echo "<br><br>";
  echo "=======相关天气指数=======<br>";
  echo "穿衣指数:".$data['today']['dressing_index']." , ".$data['today']['dressing_advice']."<br>";
  echo "紫外线强度:".$data['today']['uv_index']."<br>";
  echo "舒适指数:".$data['today']['comfort_index']."<br>";
  echo "洗车指数:".$data['today']['wash_index'];
  echo "<br><br>";
}else{
  echo $ipWeatherResult['error_code'].":".$ipWeatherResult['reason'];
}

四、根据GPS坐标来获取对应地区的天气

无论通过二、三、四获取的天气预报,因为聚合格式都是统一的,所以解析的流程是一致的,所以没有额外的操作,只是传参上有点的差异。

$geoWeatherResult = $weather->getWeatherByGeo(116.401394,39.916042);
if($geoWeatherResult['error_code'] == 0){  //以下可根据实际业务需求,自行改写
  //////////////////////////////////////////////////////////////////////
  $data = $geoWeatherResult['result'];
  echo "=======当前城市=======<br>";
  echo $data['today']['city'];
  echo "<br><br>";
  echo "=======当前天气实况=======<br>";
  echo "温度:".$data['sk']['temp']."  ";
  echo "风向:".$data['sk']['wind_direction']."  (".$data['sk']['wind_strength'].")";
  echo "湿度:".$data['sk']['humidity']."  ";
  echo "<br><br>";
  echo "=======未来几天天气预报=======<br>";
  foreach($data['future'] as $wkey =>$f){
    echo "日期:".$f['date']." ".$f['week']." ".$f['weather']." ".$f['temperature']."<br>";
  }
  echo "<br><br>";
  echo "=======相关天气指数=======<br>";
  echo "穿衣指数:".$data['today']['dressing_index']." , ".$data['today']['dressing_advice']."<br>";
  echo "紫外线强度:".$data['today']['uv_index']."<br>";
  echo "舒适指数:".$data['today']['comfort_index']."<br>";
  echo "洗车指数:".$data['today']['wash_index'];
  echo "<br><br>";
}else{
  echo $geoWeatherResult['error_code'].":".$geoWeatherResult['reason'];
}


      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/5832.html