首先,在function.php方法文件中封裝一個獲取header頭文件的方法。php
if (!function_exists('getallheaders')) {
function getallheaders() {
$headers = array();
foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
return $headers;
}
}html
而後,在相應控制器中調用該方法獲取數據,先檢查session中有沒有位置信息。git
if(!$_SESSION['MyLocation'])
{
//獲取定位座標
$location = getallheaders();
$this->get_location($location); //調用封裝的方法
}json
最後,封裝一個方法,用來請求百度接口返回具體位置信息,並存到session中。api
public function get_location($location)
{
$lat = $location['Latitude'];
$lng = $location['Longitude'];
if($lat && $lng)
{
$url = 'http://api.map.baidu.com/geocoder/v2/?ak=5BFNbSgnVF5g2O72NpvTDxFm&location=' . $lat . ',' . $lng . '&output=json&pois=1';
$html = json_decode(file_get_contents($url),true);
if($html)
{
$myLocation = array(
'city' => $html['result']['addressComponent']['city'],
'addr' => isset($html['result']['addressComponent']['street']) ? $html['result']['addressComponent']['street'] : $html['result']['formatted_address'],
'lng' => $html['result']['location']['lng'],
'lat' => $html['result']['location']['lat'],
);
$_SESSION['MyLocation'] = $myLocation;
}
}
}session