Java –使用IP地址查找位置

地理位置

在此示例中,我们向您展示如何使用IP地址查找位置(国家,城市,纬度,经度)。

1. GeoLite数据库

MaxMind提供免费的GeoLite数据库(IP地址到位置)。

  1. 在此处免费获取免费的GeoLite数据库
  2. 在此处获取GeoIP客户端Java API
  3. 开始编码。

2. GeoLite Java示例

使用GeoIP客户端Java API通过IP地址查找位置的示例。

GetLocationExample.java
package com.mkyong.analysis.location;

import java.io.File;
import java.io.IOException;
import com.maxmind.geoip.Location;
import com.maxmind.geoip.LookupService;
import com.maxmind.geoip.regionName;
import com.mkyong.analysis.location.mode.ServerLocation;

public class GetLocationExample {

  public static void main(String[] args) {
	GetLocationExample obj = new GetLocationExample();
	ServerLocation location = obj.getLocation("206.190.36.45");
	System.out.println(location);
  }

  public ServerLocation getLocation(String ipAddress) {

	File file = new File(
	    "C:\\resources\\location\\GeoLiteCity.dat");
	return getLocation(ipAddress, file);

  }

  public ServerLocation getLocation(String ipAddress, File file) {

	ServerLocation serverLocation = null;

	try {

	serverLocation = new ServerLocation();

	LookupService lookup = new LookupService(file,LookupService.GEOIP_MEMORY_CACHE);
	Location locationServices = lookup.getLocation(ipAddress);

	serverLocation.setCountryCode(locationServices.countryCode);
	serverLocation.setCountryName(locationServices.countryName);
	serverLocation.setRegion(locationServices.region);
	serverLocation.setRegionName(regionName.regionNameByCode(
             locationServices.countryCode, locationServices.region));
	serverLocation.setCity(locationServices.city);
	serverLocation.setPostalCode(locationServices.postalCode);
	serverLocation.setLatitude(String.valueOf(locationServices.latitude));
	serverLocation.setLongitude(String.valueOf(locationServices.longitude));

	} catch (IOException e) {
		System.err.println(e.getMessage());
	}

	return serverLocation;

  }
}

输出量

ServerLocation [countryCode=US, countryName=United States, region=CA, 
	regionName=California, city=Sunnyvale, postalCode=94089, 
	latitude=37.424896, longitude=-122.0074]

参考文献

  1. 维基百科:地理定位软件
  2. GeoLite免费可下载数据库

翻译自: https://mkyong.com/java/java-find-location-using-ip-address/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值