根据ip获取坐标

作者: 佛爷石 | 来源:发表于2020-09-01 21:43 被阅读0次

一、 先上效果:

https://tools.zzphoenix.com/?ip=116.85.23.218

image-20200901213237724.png

二、实现方式:

我们根据maxmind提供的数据库文件来获取

三、获取相应的文件:

https://mirrors-cdn.liferay.com/geolite.maxmind.com/download/geoip/database/GeoLiteCity-latest.zip

四、jar包引入:

<!-- 定义版本号 -->
<properties>
    <java.version>1.8</java.version>
    <geoip-api.version>1.2.15</geoip-api.version>
</properties>
<!-- 引入相应jar包 -->
<dependency>
    <groupId>com.maxmind.geoip</groupId>
    <artifactId>geoip-api</artifactId>
    <version>${geoip-api.version}</version>
</dependency>

五、Java代码 文件copy类 FileCopy.java:

public class FileCopy implements CommandLineRunner { // 这里是文件copy,从jar包中,copy到绝对路径下
    @Override
    public void run(String... args) throws Exception {
        InputStream stream = getClass().getClassLoader().getResourceAsStream("ip/GeoLiteCity.dat");
        File targetFile = new File("/usr/local/mytools/GeoLiteCity.dat");
        FileUtils.copyInputStreamToFile(stream, targetFile);
    }
}

六、工具类IpUtil.java:

    public static Location getCityByIp(String ip) {
        Location location = null;
        try {
            File  sourceFile = ResourceUtils.getFile("/usr/local/mytools/GeoLiteCity.dat"); // 这里是绝对路径
            LookupService lookupService = new LookupService(
                    sourceFile, LookupService.GEOIP_MEMORY_CACHE);
            location = lookupService.getLocation(ip);
            System.out.println(JSON.toJSON(location));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return location;
    }

七、代码位置:

码云位置: https://gitee.com/mengxisoft/maxmind

八、微信号:

有任何疑问,可加微信交流


code.jpg

相关文章

网友评论

    本文标题:根据ip获取坐标

    本文链接:https://www.haomeiwen.com/subject/ycdbsktx.html