第一步获取用户ip地址
/**
* 获取用户真实 IP
*/
public function getIP()
{
static $realip;
if (isset($_SERVER)){
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
$realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
} else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
$realip = $_SERVER["HTTP_CLIENT_IP"];
} else {
$realip = $_SERVER["REMOTE_ADDR"];
}
} else {
if (getenv("HTTP_X_FORWARDED_FOR")){
$realip = getenv("HTTP_X_FORWARDED_FOR");
} else if (getenv("HTTP_CLIENT_IP")) {
$realip = getenv("HTTP_CLIENT_IP");
} else {
$realip = getenv("REMOTE_ADDR");
}
}
return $realip;
}
第二步通过IP地址利用百度接口获取位置
1、申请百度ak http://lbsyun.baidu.com/apiconsole/key
2、 开始获取地理位置
$content =file_get_contents("http://api.map.baidu.com/location/ip?ak=27d76708ab31eed8028e135ab******&ip=".$ip."&coor=bd09ll");
php后台逻辑直接复制修改ak和自由更换ip参数其他不变
$json = json_decode($content,true);//解析json
if($json['status']!=0)
{
return "定位失败";
exit();
}
通过status判断是否获取成功,如果==0表示获取成功,如果不等于=均为获取失败。调试时候可以直接打野错误内容即可。
$arr = $json['content']['address_detail']['city'];//解析json获取市级名称,至于获取其他参数请参考正确返回值
【{"address":"CN|\u5b89\u5fbd|\u5408\u80a5|None|CHINANET|0|0","content":{"address":"\u5b89\u5fbd\u7701\u5408\u80a5\u5e02","address_detail":{"city":"\u5408\u80a5\u5e02","city_code":127,"district":"","province":"\u5b89\u5fbd\u7701","street":"","street_number":""},"point":{"x":"117.28269909","y":"31.86694226"}},"status":0}】
if(isset($arr))
{
return str_replace("市","",$arr);//返回市级单位 这里是去除获取的市级名称中的市
}else{
return "合肥";
}
完结了,代码直接复制就可以是哟个