25

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

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

worbel
  • 6,509
  • 13
  • 53
  • 63
  • What exactly do you mean? Do you want to retrieve coordinates from a GPS device or find the location based on an IP address or look up coordinates of certain destinations in a database or something else? – Wolfgang Sep 12 '09 at 19:10
  • Is this for a desktop application that needs to do it off-line? Or are web services OK to use? – Thomas Owens Sep 12 '09 at 19:15

2 Answers2

19

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.

Here is how:

Add this Maven artifact:

<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

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 .

Marquez
  • 5,891
  • 3
  • 31
  • 40
1

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

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.

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)

Denilson Sá Maia
  • 47,466
  • 33
  • 109
  • 111