準備工作
您需要登錄騰訊地圖,獲取KEY密鑰。我們使用的是騰訊地圖-WebService API?功能。
代碼示例
<?php
$ip = '14.17.101.214';
$key = 'ALWBZ-BO6CU-7YKVS-BIXH2-55VX5-RKBED';
$map = getLocationInfo($ip,$key);
echo "當前IP地址:".$map['result']['ip'];
echo "當前緯度:".$map['result']['location']['lat']."經度:".$map['result']['location']['lng'];
function getLocationInfo($ip,$key){
//$ip 用戶的當前IP地址
//$key 騰訊地圖開發者需要的KEY秘鑰,自己去注冊一下吧
//$url 騰訊地圖API請求接口地址
$url = 'https://apis.map.qq.com/ws/location/v1/ip?ip='.$ip.'&key='.$key;
$info = file_get_contents($url); //GET請求,記住這里必須要用GET哦
$info = json_decode($info, true); //解碼JSON并返回數組將
return $info; //返回請求結果
};
?>
注意:上述代碼中的變量$key,隨時可能失效,還請您替換為自己獲取的KEY。
示例效果
當前IP地址:14.17.101.214當前緯度:22.54286經度:114.05956
代碼解釋
本質上,是通過騰訊地圖API接口,獲取一個JSON并打印的過程。
返回的JSON
{
"status": 0,
"message": "Success",
"request_id": "c8c220d31e2349679704b1b0e288e03d",
"result": {
"ip": "14.17.101.214",
"location": { "lat": 22.54286, "lng": 114.05956 },
"ad_info": {
"nation": "中國",
"province": "廣東省",
"city": "深圳市",
"district": "",
"adcode": 440300
}
}
}
代碼參考:
- https://blog.csdn.net/cocosinu/article/details/122432515
- https://www.runoob.com/php/php-arrays-multi.html