最近的項目中遇到了一個實時天氣顯示的問題.經過高德地圖的開放 API 解決了;
將思路留下.
已經將它封裝成了一個函數. 能夠直接拿去使用. 不過使用前最好仍是測試一下;
思路:php
首先經過調用高德地圖IP定位的 API; http://lbs.amap.com/api/webservice/guide/api/ipconfig 獲取的 IP 定位信息中有 adcode;(好像是高德的一組城市地理信息編號吧) 而後經過調用高德的天氣查詢的 Api; http://lbs.amap.com/api/webservice/guide/api/weatherinfo/ 結合以前IP定位得到的adcode和你的密鑰;
該類使用步驟
在高德官網申請一個web的祕鑰. 而後實例化一個對象. 調用方法info. 方法的參數填上你申請的祕鑰,返回值就是你目前ip所在地的天氣;web
<?php class nansongWeather{ //得到天氣信息 public function info($key) { //$key = '你在高德申請的祕鑰'; $ipInfo = $this->ipInfo($key); //調用方法得到 Ip 定位信息; $city = $ipInfo->adcode; //得到adcode; $weatherInfo = $this->weatherInfo($key, $city); //已經獲取了天氣信息; return $weatherInfo; } //定位信息 public function ipInfo($key) { $ch = curl_init("http://restapi.amap.com/v3/ip?key=".$key); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 請求的數據不直接發送到瀏覽器 $result = curl_exec($ch); //執行請求,直接發送到瀏覽器 // $city = json_decode($result)->adcode; $info = json_decode($result); return $info; } //天氣信息 public function weatherInfo($key, $city) { $ch = curl_init("http://restapi.amap.com/v3/weather/weatherInfo?city=" . $city ."&key=" . $key); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($ch); $info = json_decode($result)->lives[0]; return $info; } }
結果如圖 注意:得到的是對象json