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
The Geolocation API is accessed via a call to navigator. geolocation ; this will cause the user's browser to ask them for permission to access their location data. If they accept, then the browser will use the best available functionality on the device to access this information (for example, GPS).
Forward geocoding lets you convert location text into geographic coordinates, and reverse geocoding turns geographic coordinates into place names. You'll find the wrapper for the Mapbox Geocoding API in the mapbox-java-services module. MapboxGeocoding is used to request both forward and reverse geocoding information.
Geolocation uses smart technology that allows addresses to be returned in real-time. These addresses are based on geocodes that come from the location services on your device, mainly the GPS (the Global Positioning System).
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 .
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With