专栏名称: ImportNew
伯乐在线旗下账号,专注Java技术分享,包括Java基础技术、进阶技能、架构设计和Java技术领域动态等。
目录
相关文章推荐
芋道源码  ·  Spring Boot集成iText实现电子签章 ·  17 小时前  
芋道源码  ·  DeepSeek 装进 ... ·  17 小时前  
芋道源码  ·  SpringBoot3.0新特性尝鲜,秒启动 ... ·  昨天  
Java编程精选  ·  为什么不建议用 equals 判断对象相等? ·  3 天前  
Java编程精选  ·  前阿里员工:内推了个38岁的研发,简历到HR ... ·  2 天前  
51好读  ›  专栏  ›  ImportNew

如何把 IP 转换成经纬度

ImportNew  · 公众号  · Java  · 2017-04-11 12:08

正文

(点击 上方公众号 ,可快速关注)


来源:xingoo,

www.cnblogs.com/xing901022/p/5981903.html

如有好文章投稿,请点击 → 这里了解详情


最国产的方式,就是使用百度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",#定位结果唯一ID

radius: 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 +"\n"+







请到「今天看啥」查看全文