Using Location-Enabled MIDlets for Mobile Navigation

Implementing the Location API

To determine location by finding the current latitude and longitude, you have to declare a class that is runnable and also a listener. Runnable is required because you want the instantiated class to be a thread that is constantly running, so it can get updates of the user's current position and send them to the application. The application will use the updates to reposition the coordinates on the screen map. The listener functionality is added because whenever there is a location change, the listener will automatically be notified.

The declaration of the class called LocPos in the sample NetBeans project for this article is:

public class LocPosition implements Runnable, LocationListener {

You first need a LocationProvider object and a Location object to store the latitude and longitude. After declaring these objects, you have to establish the criteria for getting the location from the LocationProvider (through the satellites). The following code snippet does this:

Then you initialize the LocationListener for the provider object obtained:

provider.setLocationListener(this,-1,-1,-1); /*setting up the location listener with default values so that locationUpdated() function is called when there is a change in location */

Once the LocationProvider is initialized, you also need to implement the locationUpdated method, which will be invoked by the listener process every time a change in location occurs. Because this method is triggered only when a location change occurs, it gets the coordinates from the Location object and locPos. It also gets the time stamp of the reading, as shown in this code snippet:

The full listing of Location.java is available in Listing 1. Location.java implements all the features for initializing the location provider and getting the updates of the new position in the listener process when changes to location occur.