根据IP定位地理位置

背景:

项目在海外运行,需要根据IP获取国家,城市,经纬度等信息,但是,百度地图、高德地图、淘宝等API的使用不了,而谷歌地图的又有频率限制,于是网上各种搜索,找到 GeoLiteCity.dat,GeoLiteCity.dat就好比一个本地的数据库文件,方法如下:

引入依赖:

<dependency>
    <groupId>com.maxmind.geoip</groupId>
    <artifactId>geoip-api</artifactId>
    <version>1.3.1</version>
</dependency>
复制代码

测试类如下:

public class IPTest {

    public static void main(String[] args) {
        try {
            LookupService cl = new LookupService("C:\\GeoLiteCity.dat", LookupService.GEOIP_MEMORY_CACHE);
            Location l2 = cl.getLocation("128.1.35.120");

            System.out.println(
                    "countryCode: " + l2.countryCode +"\n"+
                            "countryName: " + l2.countryName +"\n"+
                            "region: " + l2.region +"\n"+
                            "city: " + l2.city +"\n"+
                            "latitude: " + l2.latitude +"\n"+
                            "longitude: " + l2.longitude);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
复制代码

运行结果如下:

countryCode: TH
countryName: Thailand
region: 40
city: Bangkok
latitude: 13.753998
longitude: 100.5014
复制代码

项目中使用如下:

import com.maxmind.geoip.Location;
import com.maxmind.geoip.LookupService;

/**
 * @author: xbq
 * @Date: 2018/8/1 09:35
 */
@Service
public class LoadIp {

    private LookupService cl;

    @PostConstruct
    public void init() {
        try {
            cl = new LookupService(systemConstants.getIpDb(), LookupService.GEOIP_MEMORY_CACHE);
        } catch (IOException e) {
            CusLogger.error("加载ip纯真库异常:" + e.getMessage(), e);
        }
    }

	
	/**
     * 使用
     * @param ip
     * @return
     */
	public void fun(String ip) {
		// 根据ip来判定国家地区
		if(cl != null) {
			Location l2 = null;
			l2 = cl.getLocation(ip);
			if(l2 != null) {
				// 获取国家编码
				String countryCode = l2.countryCode;
				// 获取国家名称
				String countryName = l2.countryName;
				// 获取城市
				String city = l2.city;
				// 业务处理 ...
				
			}
		}
	}
}
复制代码

欢迎关注我的公众号~ 搜索公众号: 翻身码农把歌唱 或者 扫描下方二维码:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值