在本篇文章裏小編給大家整理了關於php根據地址獲取百度地圖經緯度的實例方法,有需要的朋友們可以學習下。
首先我們來看全部實例代碼:
/** * @param string $address 地址 * @param string $city 城市名 * @return array */ function getLatLng($address=‘‘,$city=‘‘) { $result = array(); $ak = ‘‘;//您的百度地圖ak,可以去百度開發者中心去免費申請 $url ="http://api.map.baidu.com/geocoder/v2/?callback=renderOption&output=json&address=".$address."&city=".$city."&ak=".$ak; $data = file_get_contents($url); $data = str_replace(‘renderOption&&renderOption(‘, ‘‘, $data); $data = str_replace(‘)‘, ‘‘, $data); $data = json_decode($data,true); if (!empty($data) && $data[‘status‘] == 0) { $result[‘lat‘] = $data[‘result‘][‘location‘][‘lat‘]; $result[‘lng‘] = $data[‘result‘][‘location‘][‘lng‘]; return $result;//返回經緯度結果 }else{ return null; } }
擴展閱讀:
官方方法總結:
/** * 搜索地址,查詢周邊的位置 () */ public function query_address($key_words){ $header[] = 'Referer: http://lbs.qq.com/webservice_v1/guide-suggestion.html'; $header[] = 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'; $url ="http://apis.map.qq.com/ws/place/v1/suggestion/?®ion=&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&keyword=".$key_words; $ch = curl_init(); //設置選項,包括URL curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch,CURLOPT_HTTPHEADER,$header); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); //執行並獲取HTML文檔內容 $output = curl_exec($ch); // print_r($output);die; //釋放curl句柄 curl_close($ch); // return $output; $result = json_decode($output,true); // print_r($result); // $res = $result['data'][0]; return $result; //echo json_encode(['error_code'=>'SUCCESS','reason'=>'查詢成功','result'=>$result); }
示例:
返回值:有很多與參數地址相近的經緯度(一般默認取第一條數據,也就是下標是0的那條經緯度)
if(!empty($result['data'][0])){ $address = $result['data'][0]; // var_dump($result) ; sleep(0.5); //print_r($address); $lat2 = $address['location']['lat']; $lng2 = $address['location']['lng']; }
以上就是本次介紹的全部知識點內容,感謝大家對神馬文庫的支持。