首先要获得客户端的真实IP地址
java代码:
/**
* 获得客户端真实IP地址
* @param request 客户端请求
* @return
*/
public static String getIp(HttpServletRequest request){
String ipAddress = request.getHeader("x-forwarded-for");
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
//根据网卡取本机配置的IP
InetAddress inet=null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress= inet.getHostAddress();
}
}
//对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
if(ipAddress.indexOf(",")>0){
ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
}
}
return ipAddress;
}
在controller里调用这个方法
/**
* @Description 获得客户端真实ip
* @param request 客户端请求
* @return
*/
@RequestMapping(value = "/getIp")
@ResponseBody
public Map getIp(HttpServletRequest request){
Map map=new HashMap();
map.put("ip",IpUtil.getIp(request))
return map;
}
js代码:
$(function () {
//浏览器定位
getLocation();
});
/**
* 浏览器定位
*/
function getLocation() {
//获得客户端的真实ip
$.ajax({
url:"/front/getIp",
type:"POST",
dataType:"JSON",
success:function (data) {
//获得ip地址
var ip=data.ip;
//调用百度定位接口
var api="http://api.map.baidu.com/location/ip?ip="+ip+"&ak=你的密钥&coor=bd09ll&callback=setPosition";
$.getScript(api);
}
});
}
/**
* 百度定位接口回调函数
* @param data 位置信息
*/
function setPosition(data) {
//data即为客户端的位置信息
alert(data.content.address_detail.city);//data.content.address_detail.city 获得城市信息 具体请查看百度API文档
}
百度ip定位接口:http://api.map.baidu.com/location/ip?ip="+ip+"&ak=你的密钥&coor=bd09ll&callback=回调函数
百度ip定位接口文档:http://lbsyun.baidu.com/index.php?title=webapi/ip-api