根据ip地址获取地理位置及坐标(离线方式)

根据ip获取地理位置信息,不用http和webservice接口,减少请求时间。我们可以利用了GeoLite2 库,GeoLite2 数据库是一个免费的 IP 地理定位数据库,GeoLite2 Country 与 City 数据库在每月的第一个周二更新。GeoLite2 ASN 数据库的更新时间为每周二。

数据库下载 : https://dev.maxmind.com/zh-hans/geoip/geoip2/geolite2/#i

java文档: http://maxmind.github.io/GeoIP2-java/

以下是一个工具类demo

1. 首先将下载好的文件放置的resources 目录下,这利用的是city数据库

2. 工具类编写

/**
 * ip地理坐标获取工具类
 */
public class Geoip2Client {

    public static Map<String,Object>  getGenIp(String ipAddr){
        Map<String,Object> result = new HashMap<>();
        try{
            String dbPath = this.getClass().getClassLoader().getResource("GeoLite2-City.mmdb").getPath();
            // 这是GeoIP2 或 GeoLite2 database 文件所在的位置 ,此处从项目resources路径下获取,当然也可以写成绝对路径
            File database = new File(dbPath);

            DatabaseReader reader = new DatabaseReader.Builder(database).withCache(new CHMCache()).build();

            InetAddress ipAddress = InetAddress.getByName(ipAddr);

            CityResponse response = reader.city(ipAddress);

            Country country = response.getCountry();
            Subdivision subdivision = response.getMostSpecificSubdivision();
            City city = response.getCity();
            Location location = response.getLocation();

            result.put("lat",location.getLatitude());//纬度
            result.put("long",location.getLongitude()); // 经度
            result.put("country",country.getNames().get("zh-CN"));// 国家名
            result.put("subdivision",subdivision.getNames().get("ja"));//省份
            result.put("city",city.getNames().get("ja")); // 城市


        } catch( Exception e){
            e.printStackTrace();
        }
        return result;
    }

}

 

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值