Sorry about the red box, but we really need you to update your browser. Read this excellent article if you're wondering why we are no longer supporting this browser version. Go to Browse Happy for browser suggestions and how to update.

Retrieving a location using geolocation

The geolocation service provides an approximate location of the BlackBerry device by using cell tower positioning and WLAN access points. The approximate location is within 200 meters to 5 kilometers of the location of the device when cell tower positioning is used, and 30 to 500 meters when WLAN access points are used. GPS technology is not required on the device for your application to use the geolocation service, so it is ideal for applications that require only an approximate location and that are used indoors (for example, applications that recommend local points of interest).

When your app retrieves location information from the geolocation service, the cell tower and WLAN access points are stored locally on the device. The next time your app retrieves location information, the cache is checked first and if the location is the same, the data is returned from the cache. Accessing the cache helps to minimize bandwidth usage and provide faster responses.

Access to the geolocation service can be controlled by the BlackBerry device user in the options on the device, by an IT policy on the BlackBerry Enterprise Server, or by the wireless service provider.

Cell tower geolocation is supported on devices that run BlackBerry Device Software 5.0 or later. Geolocation using WLAN access points is supported on devices that run BlackBerry Device Software 6.0 or later.

Geolocation modes

With 6.0 and later, you can retrieve geolocation information by specifying one of the following modes that are provided in the LocationInfo class ( net.rim.device.api.gps package):

Mode

Description

GEOLOCATION_MODE

This mode retrieves a location from the currently available geolocation sources, based on factors such as network connectivity, location accuracy, and data availability.

GEOLOCATION_MODE_CELL

This mode retrieves a location based on cell tower positioning.

GEOLOCATION_MODE_WLAN

This mode retrieves a location based on WLAN access points positioning.

BlackBerry devices that do not support geolocation can use cell tower positioning to retrieve a location, but can't use WLAN. Cell site geolocation might be provided by some wireless service providers on the CDMA network.

In 5.0, the geolocation service provides location information by using cell tower positioning. To retrieve a location by using geolocation, you must specify GPSInfo.GPS_MODE_CELLSITE as the mode.

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();

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

Verify that the BlackBerry device or BlackBerry Smartphone Simulator can access 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.*;

//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 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());
    }
}

//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;

//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));

//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() 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);
    }

//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() 
//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);

//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() to display the error message for a LocationException.  
                    try
                    {
                        BlackBerryLocationProvider myProvider = (
                                BlackBerryLocationProvider)LocationProvider
                                .getInstance(myCriteria);

//In the second try block, create a third try/catch block to retrieve the 
//location information. Invoke BlackBerryLocationProvider.getLocation() 
//to retrieve a location provider. 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. 
//In the first catch block, invoke showException() 
//to display the error message for an InterruptedException. In the second catch block, 
//invoke showException() to display the error message for a LocationException.  
                        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();
    }

//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);
            }
        });
    }

//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());
            }
        });
    }
}