Retrieve location information by using the Location class

You can request a GPS fix and then retrieve the latitude, longitude, velocity, course heading, time stamp, and the number of satellites that the BlackBerry® device is tracking.

  1. Import the required classes.
    import javax.microedition.location.*;
  2. Create a class and a constructor.
    public class handleGPS
    {
        public handleGPS()
        {
        }
    }
  3. In the class, declare static fields for a thread and for each item of location information that you retrieve.
    static GPSThread gpsThread;
    static double latitude;
    static double longitude;
    static float  heading;
    static float  velocity;
    static long   timeStamp;
    static String nmeaString;
  4. In the constructor, create and start a thread.
    gpsThread = new GPSThread();
    gpsThread.start();
  5. In the class, create a private static class that extends Thread, and create a run() method.
    private static class GPSThread extends Thread
    {
       public void run()
       {
       }
    }
  6. In run(), create an instance of the Criteria class. Invoke setCostAllowed(false) to specify the autonomous mode.
    Criteria myCriteria = new Criteria();
    myCriteria.setCostAllowed(false);
  7. In run(), create a try/catch block. In this block create an instance of the LocationProvider class by getting an instance of the Criteria object. Create a try/catch block within this block, and create an instance of the Location class to retrieve the current GPS fix including a 300 second timeout expiry. Populate the fields, and specify the number of satellites by invoking getExtraInfo("application/X-jsr179-location-nmea").
    try
    {
       LocationProvider myLocationProvider =
          LocationProvider.getInstance(myCriteria);
    
       try
       {
          Location myLocation = myLocationProvider.getLocation(300);
    
          latitude   = myLocation.getQualifiedCoordinates().getLatitude();
          longitude  = myLocation.getQualifiedCoordinates().getLongitude();
          velocity   = myLocation.getSpeed();
          heading    = myLocation.getCourse();
          timeStamp  = myLocation.getTimestamp();
          nmeaString = myLocation.getExtraInfo
             ("application/X-jsr179-location-nmea");
       }
       catch ( InterruptedException iex )
       {}
       catch ( LocationException lex )
       {}
    }
    catch ( LocationException lex )
    {}
    
    return;

Was this information helpful? Send us your comments.