本页目录
准备工作
您需要登录腾讯地图,获取 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