js实现根据IP定位用户所在城市信息
1.调用新浪IP地址库
新浪提供了开放的IP地址库数据供开发者调用,调用地址:
http://int.dpool.sina.com.cn/iplookup/iplookup.php,即可返回当前ip所在的省市信息。
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.cityselect.js"></script>
<script type="text/javascript" src="http://int.dpool.sina.com.cn/iplookup/iplookup.php?
format=js"></script>
我们先载入jquery库和cityselect城市下拉插件,然后调用新浪的IP地址库,并以js的形式返回,当然如果你想查询某一指定IP所在的城市信息可以使用接口地址如:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=123.123.123.123,将参数ip值换成指定的IP地址即可。
本地js调用:
var myprovince = remote_ip_info['province'];
var mycity = remote_ip_info['city']
var mydistrict = remote_ip_info['district'];
$(function(){
$("#city_1").citySelect({
prov:myprovince,
city:mycity
});
});
HTML代码为:
<h3>调用新浪IP库接口</h3>
<p>您所在的城市是:<script>document.write(myprovince+' '+mycity);</script></p>
<div id="city_1">
<select class="prov"></select>
<select class="city"></select>
</div>
2.调用淘宝IP地址库
淘宝也提供了比较权威的IP地址库,调用地址:http://ip.taobao.com/service/getIpInfo.php?ip=123.123.123.123,返回对应IP的省市相关信息。
调用方法:
$(function(){
$.getJSON("getTaoIP.php",function(json){
var myprovince2 = json.data.region;
var mycity2 = json.data.city;
$("#city_2").html("您所在的城市是:"+myprovince2+mycity2);
});
});
getTaoIP.php用来获取淘宝的对应IP的省市信息,返回的是json格式的数据。
$ip = get_client_ip(); //获取当前用户的ip
$url = "http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
$data = file_get_contents($url); //调用淘宝接口获取信息
echo $data;
get_client_ip()用来获取本地用户的IP地址。
//获取用户真实IP
function get_client_ip() {
if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
$ip = getenv("HTTP_CLIENT_IP");
else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"),
"unknown"))
$ip = getenv("HTTP_X_FORWARDED_FOR");
else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
$ip = getenv("REMOTE_ADDR");
else if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR']
&& strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
$ip = $_SERVER['REMOTE_ADDR'];
else
$ip = "unknown";
return ($ip);
}
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <style type="text/css"> body, html,#allmap {width: 100%;height: 100%;overflow: hidden;margin:0;font-family:"微软雅黑";} </style> <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=您的密钥"></script> <title>IP定位获取当前城市</title> </head> <body> <div id="allmap"></div> </body> </html> <script type="text/javascript"> // 百度地图API功能 var map = new BMap.Map("allmap"); var point = new BMap.Point(116.331398,39.897445); map.centerAndZoom(point,12); function myFun(result){ var cityName = result.name; map.setCenter(cityName); alert("当前定位城市:"+cityName); } var myCity = new BMap.LocalCity(); myCity.get(myFun); </script>