百度地图api根据用户IP获取用户位置(PHP)
1.百度地图开放平台找的你的ak ,链接:http://lbsyun.baidu.com/apiconsole/key
2.获取用户ip地址(外网ip 服务器上可以获取用户外网Ip 本机ip地址只能获取127.0.0.1) ,可利用下面函数,或者$_SERVER
[
"REMOTE_ADDR"
]
function getip(){
if(!empty($_SERVER["HTTP_CLIENT_IP"])){
$cip = $_SERVER["HTTP_CLIENT_IP"];
}
else if(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])){
$cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
}
else if(!empty($_SERVER["REMOTE_ADDR"])){
$cip = $_SERVER["REMOTE_ADDR"];
}
else{
$cip = '';
}
preg_match("/[\d\.]{7,15}/", $cip, $cips);
$cip = isset($cips[0]) ? $cips[0] : 'unknown';
unset($cips);
return $cip;
}
//根据IP获取用户地址信息(其中$ak你的ak),下面只是获取到省市信息,需要其他信息可打印$info
public function get_user_addr(){
$user_ip = $this->getip();
$url = "http://api.map.baidu.com/location/ip?ak=$ak&ip=$user_ip";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
if(curl_errno($ch)) {
echo 'CURL ERROR Code: '.curl_errno($ch).', reason: '.curl_error($ch);
}
curl_close($ch);
$info = json_decode($output, true);
if($info['status'] == "0"){
$addr_info = $info['content']['address_detail']['province'].' '.$info['content']['address_detail']['city'];
}
return $addr_info;
}
备注:获取位置信息到市级
原文链接(感谢博主分享):https://www.cnblogs.com/zff193/p/4171135.html