根据IP定位地理位置

背景:

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

引入依赖:

1
2
3
4
5
<dependency>
<groupId>com.maxmind.geoip</groupId>
<artifactId>geoip-api</artifactId>
<version>1.3.1</version>
</dependency>

测试类如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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();
}
}
}

运行结果如下:

1
2
3
4
5
6
countryCode: TH
countryName: Thailand
region: 40
city: Bangkok
latitude: 13.753998
longitude: 100.5014

项目中使用如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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%