1. 程式人生 > >根據ip地址獲取地理位置及座標

根據ip地址獲取地理位置及座標

根據ip獲取地理位置資訊,不用http和webservice介面,減少請求時間。我們可以利用了GeoLite2 庫,GeoLite2 資料庫是一個免費的 IP 地理定位資料庫,GeoLite2 Country 與 City 資料庫在每月的第一個週二更新。GeoLite2 ASN 資料庫的更新時間為每週二。

以下是一個工具類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;
    }

}