PHP用腾讯地图api根据地址获取经纬度的方法
方法一:
/**
* 通过地址获取经纬度
* @param int $dic_id
* @return array
*/
public function getAddress($address = '')
{
try {
$url = 'https://apis.map.qq.com/ws/geocoder/v1/?';
$param = [
'address' => $address,
'key' => $this->map_key,
];
$string = '';
foreach ($param as $k => $v) {
$string .= $k . '=' . $v . '&';
}
$string = rtrim($string, '&');
$curl = curl_init(); // 启动一个CURL会话
curl_setopt($curl, CURLOPT_URL, $url . $string);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
//curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true); // 从证书中检查SSL加密算法是否存在
$output = curl_exec($curl); //返回api的json对象
//关闭URL请求
curl_close($curl);
$result = json_decode($output, true);
if (isset($result) && $result['status']==0) {
$this->json($result['result']['location'],'success',200);
} else {
$this->json([],'faile',-1);
}
} catch (\Exception $e) {
$this->json([],'faile',0);
}
}
其中的map_key,是你申请的腾讯地图的key。
方法二:
/**
* 搜素地址获得经纬度,解决小程序定位不准的问题
* @param int $dic_id
* @return array
*/
public function getAddress_new($address = '')
{
try {
$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=".$address;
$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);
if (isset($result) && $result['status']==0) {
$this->json($result['data'][0]['location'],'success',200);
} else {
$this->json([],'faile',-1);
}
} catch (\Exception $e) {
$this->json([],'faile',0);
}
}
address是你传的地址,其他地方都不用改。
参考文章
每一次的结束都意味着新的开始