一、根据IP获取地址
/** * 根据ip获取城市(百度) */ public static function getCityByIp($ip) { $url = "http://api.map.baidu.com/location/ip?ak=32f38c9491f2da9eb61106aaab1e9739&ip=".$ip; $result = file_get_contents($url); $result = json_decode($result); $result = self::objtoarr($result); $res = []; if (is_array($result) && isset($result['status']) && $result['status'] == 0 && isset($result['content'])) { $res['province'] = $result['content']['address_detail']['province'] ?? ''; $res['city'] = $result['content']['address_detail']['city'] ?? ''; $res['lat'] = $result['content']['point']['x'] ?? ''; $res['lin'] = $result['content']['point']['y'] ?? ''; } return $res; }
/** * 根据ip获取城市(新浪) */ public static function GetIpLookup($ip = ''){ $res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip); if(empty($res)) return false; $matches = []; preg_match('#{.+?}#', $res, $matches); if(!isset($matches[0])) return false; $res = json_decode($matches[0], true); if(isset($res['ret']) && $res['ret'] == 1){ $res['ip'] = $ip; return $res; } return false; }
/** * 根据ip获取城市(淘宝) */ public static function ip_address($ip) { $durl = 'http://ip.taobao.com/service/getIpInfo.php?accessKey=alibaba-inc&ip='.$ip; // 初始化 $curl = curl_init(); // 设置url路径 curl_setopt($curl, CURLOPT_URL, $durl); // 将 curl_exec()获取的信息以文件流的形式返回,而不是直接输出。 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回 curl_setopt($curl, CURLOPT_BINARYTRANSFER, true) ; // 执行 $data = curl_exec($curl); // 关闭连接 curl_close($curl); // 返回数据 return $data; }
二、根据地址获取经纬度
获取秘钥(ak值):http://lbsyun.baidu.com/apiconsole/key?application=key#/home
/** * 根据地址获取经纬度 */ public static function getLocationByAddr($addr,$city){ //$info->result->precise //是否精确查找。1为精确查找 $url="http://api.map.baidu.com/geocoder/v2/?ak=GOxtOetIDdaBsSGt9mMwpNPqoeAvv06z&output=json&address=".$addr."&city=".$city; $result = file_get_contents($url); $result = json_decode($result); $res = []; if($result->status == 0){//返回状态值,成功返回0 $res['lng'] = $result->result->location->lng; //经度 $res['lat'] = $result->result->location->lat; //纬度 } return $res; }
/** * 根据经纬度获取地址 */ public static function getAddrByLocation($addr,$city){ $url = "http://api.map.baidu.com/geocoder/v2/?ak=GOxtOetIDdaBsSGt9mMwpNPqoeAvv06z&callback=renderReverse&location=28.696117,115.958458&output=json&pois=1"; $result = file_get_contents($url); $result = str_replace('renderReverse&&renderReverse(', '', $result); $result = substr($result, 0, strlen($result) - 1); $result = json_decode($result,1); $res = $result['result']['addressComponent'] ?? []; return $res; }