利用GeoLite2-City.mmdb开源库将IP转换成经纬度
开源库下载地址
https://dev.maxmind.com/geoip/geoip2/geolite2/
GeoLite2数据库是免费的IP地理定位数据库,但是不太准确,通过IP转换成的经纬度与真实地址相比较还有有一定偏差,大家看看官网,根据自己需求选择。
本人小Demo需求要做一个热力图,数据只有IP,需要一个工具类将IP转成经纬度
maven项目里面,我临时将放在了src/main/resources(库文件还是比较大的,根据需求选择存放位置,这只是一个Demo)
工具类如下:
public final class IpConvertUtil {
private static org.apache.log4j.Logger log = org.apache.log4j.LogManager.getLogger(IpConvertUtil.class);
//public static final String url = "/home/admin/GeoLite2-City.mmdb";
public static CityResponse coordinateTransformation(String ip) {
DatabaseReader reader = null;
CityResponse response = null;
try {
// 创建 GeoLite2 数据库(如果路径中包含中文,路径名会被转码)
String url = IpConvertUtil.class.getClassLoader().getResource("GeoLite2-City.mmdb").getPath();
//解码
String decodeStr = URLDecoder.decode(url, "utf-8");
File database = new File(decodeStr);
// 读取数据库内容
reader = new DatabaseReader.Builder(database).build();
InetAddress ipAddress = InetAddress.getByName(ip);
// 获取查询结果
response = reader.city(ipAddress);
} catch (Exception e) {
log.error("ip:" + ip + "转换经纬度失败!", e);
} finally {
if (reader != null) {
try {
reader.close();
return response;
} catch (IOException e) {
log.error("ip:" + ip + "转换经纬度失败,关闭失败!", e);
}
}
}
return response;
}
}
如果自己路径名中有中文的话,一定不要忘记解码!
通过返回的CityResponse对象里面可以获取到经纬度以及其他的信息(自己可以查下)
测试类:
@Test
@Rollback(value = false)
public void IPConvert() {
String ip = "";
CityResponse response = IpConvertUtil.coordinateTransformation(ip);
//经度
String lng = response.getLocation().getLongitude().toString();
//纬度
String lat = response.getLocation().getLatitude().toString();
System.out.println("lng:" + lng);
System.out.println("lat:" + lat);
}
结果肯定跟实际情况有一定的出入,慎重使用!
希望能帮到大家。