在 Java 中获取地理位置的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1415851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:50:50  来源:igfitidea点击:

Best way to get geo-location in Java

javageolocation

提问by Athena

What is the best way to get geo-location in Java (freely if possible)?

在 Java 中获取地理位置的最佳方法是什么(如果可能的话,免费)?

Update: Not from a GPS device. Basically how Firefox 3.5 / HTML 5 does it

更新:不是来自 GPS 设备。Firefox 3.5 / HTML 5 基本上是如何做到的

回答by Denilson Sá Maia

If you want to know how Firefox 3.5 (or Google Chrome) gets the geolocation, then please take a look here: How Google/Firefox Geolocation API works

如果您想知道 Firefox 3.5(或 Google Chrome)如何获取地理位置,请查看此处:Google/Firefox Geolocation API 的工作原理

Basically, what Firefox 3.5 (as well as Chrome) does is to get the list of nearby Wi-Fi networks and send that list using JSON to a Google webservice, which will then return the approximate coordinates.

基本上,Firefox 3.5(以及 Chrome)所做的是获取附近 Wi-Fi 网络的列表,并使用 JSON 将该列表发送到 Google 网络服务,然后该服务将返回近似坐标。

By the way, there is no Java involved in this process. To get geolocation from Firefox/Chrome, you just call a few JavaScript methods. (I really hope that you know that Java is different from JavaScript)

顺便说一下,这个过程没有涉及Java。要从 Firefox/Chrome 获取地理位置,您只需调用一些 JavaScript 方法。(我真的希望你知道 Java 与 JavaScript 不同)

回答by Marquez

An easy way is with GeoLite (http://dev.maxmind.com/geoip/legacy/geolite/). Because it uses a local database no web service calls are needed and it's much faster for geocoding large numbers of IPs.

一个简单的方法是使用 GeoLite ( http://dev.maxmind.com/geoip/legacy/geolite/)。因为它使用本地数据库,所以不需要 Web 服务调用,而且对大量 IP 进行地理编码的速度要快得多。

Here is how:

方法如下:

Add this Maven artifact:

添加此 Maven 工件:

<dependency>
    <groupId>com.maxmind.geoip</groupId>
    <artifactId>geoip-api</artifactId>
    <version>1.2.11</version>
</dependency>

Download the geolocation data file from http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz

http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz下载地理定位数据文件

Unpack the file into any folder. Then do:

将文件解压到任意文件夹中。然后做:

LookupService cl = new LookupService("/var/geolite/GeoLiteCity.dat",
                    LookupService.GEOIP_MEMORY_CACHE | LookupService.GEOIP_CHECK_CACHE);

Location location = cl.getLocation("some ip address");

The result will be in the Location object in the latitude, longitude, city, region and countryCode properties.

结果将在纬度、经度、城市、地区和国家代码属性中的位置对象中。

Please take a look at their accuracy estimates to ensure it meets the needs of your project: http://www.maxmind.com/en/geolite_city_accuracy.

请查看他们的准确度估计值,以确保它满足您项目的需求:http: //www.maxmind.com/en/geolite_city_accuracy