1. 程式人生 > 程式設計 >php如何根據IP獲取當前經緯度以及地域資訊

php如何根據IP獲取當前經緯度以及地域資訊

今天心血來潮腦海忽出一個想法,即打算寫出來玩耍一下。

其中涉及幾個關鍵功能

1.獲取使用者當前經緯度、地址、地域資訊;

2.計算使用者與使用者之間的距離、路線。

3.其他,與今天的文章沒有關係就不廢話啦。

大概翻閱了一下資料,方法有很多,今天主要介紹一下騰訊地圖的方法吧

廢話不多說直接上碼;

求請求方法:

function getLocationInfo($ip,$key){

    //$ip  使用者的當前IP地址
    //$key 騰訊地圖開發者需要的KEY祕鑰,自己去註冊一下吧
    //$url 騰訊地圖API請求介面地址
    
    $url = 'https://apis.map.qq.cowww.cppcns.com
m/ws/location/v1/ip?ip='.$ip.'&http://www.cppcns.comkey='.$key; $info = file_get_contents($url); //GET請求,記住這裡必須要用GET哦 $info = on_decode($info,true); //將返回資料轉JSON return $info; //返回請求結果 }

返回結果:

array(3) {
  ["ip"]=>
  string(12) "0.0.0.0"			//IP地址
  ["location"]=>
  array(2) {
    ["lat"]=>
    float(00.0000)				//緯度
    ["lng"]=>
    float(000.00000)			//經度
  }
  ["ad_info"]=>
  array(5) {
    ["nation"]=>
    string(6) "中國"				//國家
    ["province"]=>
    string(12) "黑龍江省"		//省
    ["city"]=>
    string(12) "哈爾濱市"		//市
    ["district"]=>
    string(9) "道里區"			//區
    ["adcode"]=>
    int(000000)					//地址碼
 
} }

就這樣麼簡單,已經拿到經緯度啦!

至於計算距離或者根據經緯度獲取當前詳細地址就都不是問題啦~!

php根據IP獲取IP所在城市

//根據現有IP地址獲取其地理位置(省份,城市等)的方法

function GetIpLookhttp://www.cppcns.comup($ip = ''){  
  if(empty($ip)){  
    return '請輸入IP地址'; 
  }  
  $res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);  
  if(empty($res)){ return false; }  
  $jsonMatches = array();  
  preg_match('#\{.+?\}#',$res,$jsonMatches);  
  if(!isset($jsonMatches[0])){ return false; }  
  $json = json_decode($jsonMatches[0],true);  
  if(isset($json['ret']) && $json['ret'] == 1){  
    $json['ip'] = $ip;  
    unset($json['ret']);  
  }else{  
    return false;  
  }  
  return $json;  
} 
$ipInfos = GetIpLookup('123.125.114.144'); //baidu.com IP地址  //ipInfos 是一個數組
var_dump($ipInfos);

總結

到此這篇關於php如何根據IP獲取當前經緯度以及地域資訊的文章就介紹到這了,更多相關php獲取當前經緯度及地域內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!