php 获取IP地址 并获取坐标lat lng 并获取到所在地区

时间:2022-10-10 21:16:52

函数方法:ps:只能放在服务器上起效果,放在本地是无法起效果的

/*
**根据ip获取坐标
***/
function get_zuobiao(){
    $user_IP = ($_SERVER["HTTP_VIA"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : $_SERVER["REMOTE_ADDR"];//获取IP
    $user_IP = ($user_IP) ? $user_IP : $_SERVER["REMOTE_ADDR"];//获取IP
    $re = os_get("http://api.map.baidu.com/location/ip?ip=".$user_IP."&ak=878f0d7785ccb5c9f46215af5faf0ebf&coor=bd09ll");//获取lat lng
    $val = json_decode($re,true); 
    $point = $val['content']['point'];
    print_r($point);//拆分的lat lnt
    $re = getcity($point['y'],$point['x']);//根据lat lng 再获取所在省市区详
    print_r($re);exit();
}



/*根据坐标获取地区*/
function getcity($lat,$lng){
    $re = file_get_contents("http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=".$lat.",".$lng."&output=xml&pois=1&ak=878f0d7785ccb5c9f46215af5faf0ebf");
    $xmlstring = simplexml_load_string($re, 'SimpleXMLElement', LIBXML_NOCDATA); 
    $val = json_decode(json_encode($xmlstring),true); 
    $city['qu'] = $val['result']['addressComponent']['district'];
    $city['city'] = $val['result']['addressComponent']['city'];
    $city['province'] = $val['result']['addressComponent']['province'];
    return $city;
}