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:
Location loc;LocationProvider provider= nulltry { Criteria crit = new Criteria(); crit.setCostAllowed(true); //default value crit.setPreferredPowerConsumption(Criteria.NO_REQUIREMENT); /*Filling up default values required for Criteria before getting instance of Location Provider */ provider = LocationProvider.getInstance(crit); } catch (LocationException ex) { ex.printStackTrace(); }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() functionOnce 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:
is called when there is a change in location */
public void locationUpdated(LocationProvider provider, Location locPos) { /* Updating of latitude, longitude, and time whenThe 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.
locationUpdated() is called on change of location */ coordinates = locPos.getQualifiedCoordinates(); sb.delete(0,sb.length()); sb.append(new Date(locPos.getTimestamp()).toString()); latitude = coordinates.getLatitude(); longitude = coordinates.getLongitude(); }
Page 2 of 4
This article was originally published on June 18, 2009