Dennis Laumen We who cut mere stones must always be envisioning cathedrals

J2ME Location API sample

Recently I have been playing around with J2ME. One of the cool features of J2ME is the Location API (JSR-179).

Firstly, remember to import the Location package.

import javax.microedition.location.*;

Let's get to the meat of the matter.

// Criteria can be used to filter which GPS device to use.
Criteria criteria = new Criteria();
criteria.setCostAllowed(true);
criteria.setPreferredPowerConsumption(Criteria.NO_REQUIREMENT);
// Get a location provider based on the aforementioned criteria.
LocationProvider provider = LocationProvider.getInstance(criteria);
// Try to fetch the current location (using a 3 minute timeout).
Location location = provider.getLocation(180);
// Get the coordinates of the current location.
Coordinates coordinates = location.getQualifiedCoordinates();
if (coordinates  != null) {
    // Get the latitude and longitude of the coordinates.
    double latitude = coordinates.getLatitude();
    double longitude = coordinates.getLongitude();
} else {
    // You didn't get any coordinates.
}

As you can see it's pretty easy fetching your position's latitude and longitude. It's not a piece of navigation software yet, but it's a pretty cool first step.