Retrieving the location of a device by using the geolocation service

You can use the geolocation service to retrieve the location of a BlackBerry device by performing the following actions (which are similar to the actions involved in retrieving a GPS location):

  1. Specify a geolocation mode in a BlackBerryCriteria object.
  2. Retrieve a location provider.
  3. Request a single geolocation fix or multiple geolocation fixes.
  4. Retrieve the location information for the device.

Code sample: Specifying a geolocation mode

BlackBerryCriteria myCriteria = new BlackBerryCriteria(
        LocationInfo.GEOLOCATION_MODE);

Code sample: Retrieving a location provider

BlackBerryLocationProvider myProvider = (BlackBerryLocationProvider)
        LocationProvider.getInstance(myCriteria);

Code sample: Requesting a single geolocation fix or multiple geolocation fixes

/* Single location fix */
BlackBerryLocation myLocation = (BlackBerryLocation)myProvider.getLocation(timeout);
 
/* Multiple location fixes */
myProvider.setLocationListener(…);

Code sample: Retrieving the location information for the device

double lat = myLocation.getQualifiedCoordinates().getLatitude();
double lng = myLocation.getQualifiedCoordinates().getLongitude();
double alt = myLocation.getQualifiedCoordinates().getAltitude();

Retrieve the location of a device by using the geolocation service

The following steps demonstrate how to create a UI application that provides the location of the BlackBerry device by using the geolocation service.

Before you begin: Verify that the BlackBerry device or BlackBerry Smartphone Simulator can access the geolocation service.
  1. Import the required classes and interfaces.
    import net.rim.device.api.gps.*;
    import net.rim.device.api.system.Application;
    import net.rim.device.api.ui.*;
    import net.rim.device.api.ui.component.*;
    import net.rim.device.api.ui.container.*;
    
    import javax.microedition.location.*;
  2. Create the application framework by extending the UiApplication class. In main(), create an instance of the new class and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor, invoke pushScreen() to display the custom screen for the application. The GeolocationScreen class, which is described in step 3, represents the custom screen.
    public final class GeolocationDemo extends UiApplication
    {
        public static void main(String[] args)
        {
            GeolocationDemo theApp = new GeolocationDemo();
            theApp.enterEventDispatcher();
        }
        
        public GeolocationDemo() 
        {
            pushScreen(new GeolocationScreen());
        }
    }
  3. Create the framework for the custom screen by extending the MainScreen class. Create an instance of the LabelField class to store the coordinates that display on the screen. Create two double variables to store the latitude and longitude values.
    class GeolocationScreen extends MainScreen
    {
        private LabelField _coordLabel;
        private double _latitude;
        private double _longitude;
    }
  4. In the screen constructor, invoke super() to create a default menu. Invoke setTitle() to specify the title for the screen.
    public GeolocationScreen() 
    {
        super(DEFAULT_CLOSE | DEFAULT_MENU);
        setTitle(new LabelField("Geolocation Demo", Field.USE_ALL_WIDTH | 
                DrawStyle.HCENTER));
    }
  5. In the screen constructor, create an instance of the ButtonField class to create a button that the BlackBerry device user clicks to retrieve the geolocation of the device. Invoke Field.setChangeListener() to listen for changes to the button. Invoke findGeolocation(), which is described in step 6, to retrieve the geolocation when the user clicks the button. Invoke add() to add the button to the screen. Create an instance of the LabelField class to display the resulting coordinates and invoke add() to add the field to the screen.
    ButtonField geolocButton = new ButtonField("Get geolocation", 
            ButtonField.CONSUME_CLICK);
    geolocButton.setChangeListener(new FieldChangeListener()
        {
            public void fieldChanged(Field field, int context)
            {
                findGeolocation();
            }
        });
    add(geolocButton);
    
    this._coordLabel = new LabelField();
    add(this._coordLabel);
  6. Create the framework for the findGeolocation method. Invoke setText() with an empty String value to clear LabelField for the coordinates. Create an instance of the Thread class that invokes run(). This thread is used to process the retrieval of the geolocation information. In run(), create a try/catch block to specify the geolocation mode. Create an instance of the BlackBerryCriteria class by invoking BlackBerryCriteria() and pass LocationInfo.GEOLOCATION_MODE as the mode to retrieve geolocation information. In the catch block, invoke showException(), which is described in step 10, to display the error message for an UnsupportedOperationException.
    private void findGeolocation()
    {
        this._coordLabel.setText("");
                   
        Thread geolocThread = new Thread() 
        {
            public void run() 
            {
                try
                {
                    BlackBerryCriteria myCriteria = new BlackBerryCriteria(
                            LocationInfo.GEOLOCATION_MODE);
                } 
                catch (UnsupportedOperationException e) 
                {
                   showException(e);
                }
            }
        };
        geolocThread.start();
    }
  7. In the first try block, create a second try/catch block to retrieve a location provider. Invoke LocationProvider.getInstance() with the BlackBerryCriteria object to retrieve a location provider. In the catch block, invoke showException(), which is described in step 10, to display the error message for a LocationException.
    try
    {
        BlackBerryLocationProvider myProvider = (BlackBerryLocationProvider)
                LocationProvider.getInstance(myCriteria);
    }
    catch (LocationException e)
    {
        showException(e);
    }
  8. In the second try block, create a third try/catch block to retrieve the location information. Invoke BlackBerryLocationProvider.getLocation() with a parameter of -1 to retrieve a location provider by using the default timeout value. Invoke getLongitude() and getLatitude() to retrieve the longitudinal and latitudinal coordinates respectively. Create an instance of the StringBuffer class and append the resulting coordinates to the buffer. Create a String variable and invoke toString() with the StringBuffer object to return the String value for the coordinates. Invoke showResults()to display the results on the screen, which is described in step 9. In the first catch block, invoke showException(), which is described in step 10, to display the error message for an InterruptedException. In the second catch block, invoke showException(), which is described in step 10, to display the error message for a LocationException.
    try
    {
        BlackBerryLocation myLocation =(BlackBerryLocation)myProvider
                .getLocation(-1);
        _longitude = myLocation.getQualifiedCoordinates().getLongitude();
        _latitude = myLocation.getQualifiedCoordinates().getLatitude();
                                
        StringBuffer sb = new StringBuffer();
        sb.append("Longitude: ");
        sb.append(_longitude);
        sb.append("\n");
        sb.append("Latitude: ");
        sb.append(_latitude);
        String msg = sb.toString();
        showResults(msg);
    }
    catch (InterruptedException e)
    {
        showException(e);
    }
    catch (LocationException e)
    {
        showException(e);
    }
  9. In the showResults method, invoke invokeLater() to add this section of code to the event queue of the application. Create an instance of the Runnable class and pass it as a parameter to invokeLater(). Override run() in the definition of Runnable. Invoke setText() with the String variable to specify the resulting coordinates for the LabelField.
    private void showResults(final String msg)
    {
        Application.getApplication().invokeLater(new Runnable()
        {
            public void run()
            {
                GeolocationScreen.this._coordLabel.setText(msg);
            }
        });
    }
  10. In the showException method, invoke invokeLater() to add this section of code to the event queue of the application. Create an instance of Runnable and pass it as a parameter to invokeLater(). Override run() in the definition of Runnable. Invoke Dialog.alert() to create an alert dialog box, and pass the error message by invoking getMessage().
    private void showException(final Exception e) 
    {
        Application.getApplication().invokeLater(new Runnable()
        {
            public void run()
            {
                Dialog.alert(e.getMessage());
            }
        });
    }
Back To Top

Code sample: Retrieving the location of a device by using the geolocation service

The following code sample demonstrates how to create a UI application that provides the location of the BlackBerry device by using the geolocation service.

import net.rim.device.api.gps.*;
import net.rim.device.api.system.Application;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.component.*;
import javax.microedition.location.*;

public final class GeolocationDemo extends UiApplication
{
    public static void main(String[] args)
    {
        GeolocationDemo theApp = new GeolocationDemo();
        theApp.enterEventDispatcher();
    }
    
    public GeolocationDemo() 
    {
        pushScreen(new GeolocationScreen());
    }
}

class GeolocationScreen extends MainScreen 
{
    private LabelField _coordLabel;
    private double _latitude;
    private double _longitude;
          
    public GeolocationScreen() 
    {
        super(DEFAULT_CLOSE | DEFAULT_MENU);

        setTitle(new LabelField("Geolocation Demo" , Field.USE_ALL_WIDTH | 
                DrawStyle.HCENTER));
                     
        ButtonField geolocButton = new ButtonField("Get geolocation", 
                ButtonField.CONSUME_CLICK);
        geolocButton.setChangeListener(new FieldChangeListener()
        {
            public void fieldChanged(Field field, int context)
            {
                findGeolocation();
            }
        });
        add(geolocButton);
        
        this._coordLabel = new LabelField();
        add(this._coordLabel);
    }
    
    private void findGeolocation()
    {
        this._coordLabel.setText("");
               
        Thread geolocThread = new Thread() 
        {
            public void run() 
            {
                try
                {
                    BlackBerryCriteria myCriteria = new BlackBerryCriteria(
                            LocationInfo.GEOLOCATION_MODE);
                    try
                    {
                        BlackBerryLocationProvider myProvider = (
                                BlackBerryLocationProvider)LocationProvider
                                .getInstance(myCriteria);
                        try
                        {
                            BlackBerryLocation myLocation = (BlackBerryLocation)
                                    myProvider.getLocation(300);
                            _longitude = myLocation.getQualifiedCoordinates()
                                    .getLongitude();
                            _latitude = myLocation.getQualifiedCoordinates()
                                    .getLatitude();
                            
                            StringBuffer sb = new StringBuffer();
                            sb.append("Longitude: ");
                            sb.append(_longitude);
                            sb.append("\n");
                            sb.append("Latitude: ");
                            sb.append(_latitude);
                            String msg = sb.toString();
                            showResults(msg);
                        }
                        catch (InterruptedException e)
                        {
                            showException(e);
                        }
                        catch (LocationException e)
                        {
                            showException(e);
                        }
                    }
                    catch (LocationException e)
                    {
                        showException(e);
                    }
               } 
               catch (UnsupportedOperationException e) 
               {
                   showException(e);
               }
            }
        };
        geolocThread.start();
    }

    private void showResults(final String msg)
    {
        Application.getApplication().invokeLater(new Runnable()
        {
            public void run()
            {
                GeolocationScreen.this._coordLabel.setText(msg);
            }
        });
    }
    
    private void showException(final Exception e) 
    {
        Application.getApplication().invokeLater(new Runnable() 
        {
            public void run() 
            {
                Dialog.alert(e.getMessage());
            }
        });
    }
}
Back To Top
Previous topic: Geolocation modes

Was this information helpful? Send us your comments.