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']; }
相关推荐
guoyanga 2020-11-10
ALLENJIAO 2020-06-13
shilongdred 2019-11-19
nellson 2019-11-19
songyaping0 2011-07-19
xcjing 2015-11-12
随手一记 2013-08-08
xiaoshe 2014-07-10
deusrwvf 2011-10-08
minggehenhao 2019-06-30
wildelf 2015-09-17
submarineas 2019-06-30
ZZZhangbingyi 2019-06-29
Donutsapps 2019-06-28
silencexiao 2015-11-12
zhaocen0 2019-06-19
xing00 2009-08-11
数据与算法之美 2011-02-26