Welcome 微信登录

首页 / 操作系统 / Linux / 如何把IP转换成经纬度(Java版)

经常有这种需求,拥有用户的IP地址,想要在地图上显示用户的访问量。这个时候就需要用到经纬度...应为一般的地图插件都是基于经纬度的。
那么问题来了,如何把IP转换成经纬度?

百度API

最国产的方式,就是使用百度API了,百度提供了两种服务:

普通的IP服务:http://lbsyun.baidu.com/index.php?title=webapi/ip-api

https://api.map.baidu.com/location/ip?ak=请输入您的AK&coor=bd09ll返回值:{address: "CN|吉林|长春|None|CERNET|1|None",content: {address: "吉林省长春市",address_detail: {city: "长春市",city_code: 53,district: "",province: "吉林省",street: "",street_number: ""},point: { x: "125.31364243",y: "43.89833761"}},status: 0}

精准的服务:http://lbsyun.baidu.com/index.php?title=webapi/high-acc-ip

https://api.map.baidu.com/highacciploc/v1?qcip=220.181.38.113&qterm=pc&ak=请输入您的AK&coord=bd09ll返回值:{content: {location: {lat: 40.047726,#纬度lng: 116.313304 #经度},locid: "8b1bf81d208bc2ce657fb6e6c270de66",#定位结果唯一IDradius: 30, #定位结果半径confidence: 1 #定位结果可信度},result: {error: 161,#定位结果状态码loc_time: "2016-08-23 15:14:12"#定位时间}}这个API也不是随便问的,首先就需要注册;每个时间段的访问量还有限...因此不适合做数据分析使用。因为数据分析往往是大批量的数据同时去进行经纬度的转换。

Logstash进行转换

Logstash本身提供了IP地址转换成经纬度的功能:input{file{path => "D:access.json"start_position => "beginning"} }filter{json{source => "message"}date{match => ["time","yyyy-MM-dd HH:mm:ss"]timezone => "Asia/Shanghai"}geoip {source => "ip"target => "geoip"}}output{stdout{codec => rubydebug}}

MaxMind提供的GeoIp服务

这个公司提供了GeoIp的转换服务,当然如果想要精确的匹配也是收费的。这里有一个体验的网址:https://www.maxmind.com/en/geoip-demo

东拼西凑山寨方案

这个山寨的方案灵感来源于Logstash,Logstash本身提供了IP转换经纬度的功能。原理就是它自己有一个IP数据库,可以通过它执行查询。其实这个数据库时老版的MaxMind提供的数据文件,凑合用吧!新的需要花钱呀!废话不多说,在Java中想要使用这个数据文件需要下载相应的Jar包和dat文件:
  • GeoIP jar包:geoip-api-1.3.1.jar
  • Geo city dat文件:GeoLiteCity-2013-01-18.dat
把dat文件放在自己的本地目录,然后项目中导入geoip.jar即可:import com.maxmind.geoip.Location;import com.maxmind.geoip.LookupService;import java.io.IOException;public class TestMain {public static void main(String[] args) {try {LookupService cl = new LookupService("D:/lib/geoip/GeoLiteCity-2013-01-18.dat", LookupService.GEOIP_MEMORY_CACHE);Location l2 = cl.getLocation("144.0.9.29");System.out.println("countryCode: " + l2.countryCode +" "+"countryName: " + l2.countryName +" "+"region: " + l2.region +" "+"city: " + l2.city +" "+"latitude: " + l2.latitude +" "+"longitude: " + l2.longitude);} catch (IOException e) {e.printStackTrace();}}}输出内容:countryCode: CNcountryName: Chinaregion: 25city: Jinanlatitude: 36.668304longitude: 116.99719

最后晒一个图,兴奋一下

参考

1 国外Geoip服务 MaxMind:https://www.maxmind.com/en/geoip-demo
2 国内Geoip服务 百度开放API: http://lbsyun.baidu.com/index.php?title=webapi/ip-api本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-11/137319.htm