Retrieve the estimated travel time and distance

You can create an application that retrieves the estimated time and distance it takes to travel between two locations. In the following steps, a UI application is created that contains a text field in which the BlackBerry device user types a destination address, a button that the user clicks to retrieve the estimated time and distance to reach the destination, and a field to display the results.

Before you begin:

Make sure the BlackBerry device or BlackBerry Smartphone Simulator has GPS enabled.

  1. Import the required classes and interfaces.
    import net.rim.device.api.lbs.Locator;
    import net.rim.device.api.lbs.travel.*;
    import net.rim.device.api.system.*;
    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 TravelTimeScreen class, described in step 3, represents the custom screen.
    public final class MyTravelTimeDemo extends UiApplication
    {
        public static void main(String[] args)
        {
            MyTravelTimeDemo theApp = new MyTravelTimeDemo();
            theApp.enterEventDispatcher();
        }
        public MyTravelTimeDemo()
        {
            pushScreen(new TravelTimeScreen());
        }
    }
  3. Create the framework for the custom screen by extending the MainScreen class.
    class TravelTimeScreen extends MainScreen
    {
        private BasicEditField _destinationField;
        private LabelField _timeLabel;
        private LabelField _distanceLabel;
  4. In the constructor, invoke super() to create a default menu. Invoke setTitle() to specify the title for the screen. Create an instance of the BasicEditField class to create a text field for the user to type the destination in. Invoke add() to add the field to the screen. Create an instance of the ButtonField class to create a button to retrieve the travel time and distance estimate. Invoke Field.setChangeListener() to listen for changes to the button. Invoke findTravelTime(), which is described in step 5, to retrieve the travel time and distance estimate when the user clicks the button. Invoke add() to add the button to the screen. Create instances of the LabelField class to display the travel time and distance results.
    public TravelTimeScreen()
    {
        super(DEFAULT_CLOSE | DEFAULT_MENU);
    
        setTitle(new LabelField("Travel Time Demo" , Field.USE_ALL_WIDTH | DrawStyle.HCENTER));
                         
        this._destinationField = new BasicEditField("Destination: ", "", 500, TextField.NO_NEWLINE);
        add(this._destinationField);
            
        ButtonField travelButton = new ButtonField("Get Travel Estimate", ButtonField.CONSUME_CLICK);
        travelButton.setChangeListener(new FieldChangeListener() 
        {
            public void fieldChanged(Field field, int context)
            {
                findTravelTime();
            }
        });
        add(travelButton);
            
        this._timeLabel = new LabelField();
        add(this._timeLabel);
        this._distanceLabel = new LabelField();
        add(this._distanceLabel);
    }
  5. Create a method in the TravelTimeScreen class to provide the travel time estimate. Create an instance of the String class that invokes getText() to retrieve the destination that the user typed. Validate that the field is not empty by checking for a null value or for a length of 0 in the destination field. Clear the travel time and distance result fields.
    private void findTravelTime() 
    {
        final String destination = this._destinationField.getText();
        if ((destination == null) || (destination.length() == 0))
        {
            Dialog.alert("Destination field cannot be empty");
            return;
        }
    
        this._timeLabel.setText("");
        this._distanceLabel.setText("");
  6. Retrieve the geospatial coordinates for the starting and ending locations, by first creating an instance of the Thread class in the findTravelTime method that invokes run(). In run(), in a try/catch block, invoke Locator.geocode() and pass as a parameter the destination String to find the address and return an array of Landmark objects. Invoke Landmark.getQualifiedCoordinates() to retrieve the geospatial coordinates for the destination by using the geolocation service. Invoke LocationProvider.getInstance() to retrieve a location provider to request the current location. Invoke Location.getQualifiedCoordinates() to retrieve the geospatial coordinates for the current location by using GPS. Alternatively, if GPS is unavailable, you can use the geolocation service to retrieve the coordinates for the current location.
    Thread travelTimeThread = new Thread()
    {
        public void run()
        {
            try
            {
                final Landmark[] landmarks = Locator.geocode(destination.replace('\n', ' '), null);
                Coordinates endPoint = landmarks[0].getQualifiedCoordinates();
    
                LocationProvider provider = LocationProvider.getInstance(null);
                if (provider == null)
                {
                    throw new IllegalStateException("no LocationProvider available");
                }
                Coordinates startPoint = provider.getLocation(-1).getQualifiedCoordinates();
  7. Create an instance of the TravelTimeEstimator class by invoking TraveTimeEstimator.getInstance(). Invoke requestArrivalEstimate() to request the estimated travel time and distance. Specify the Coordinates objects for the starting and ending locations, and specify the starting time. In this example, a synchrous request is made because a separate thread was created to retrieve the geospatial coordinates. You can use the TravelTime.START_NOW constant to indicate that travel starts immediately. Invoke showResults(), which is described in step 8, to display the results.
    TravelTimeEstimator estimator = TravelTimeEstimator.getInstance();
    final TravelTime travelTime = estimator.requestArrivalEstimate(startPoint, endPoint, TravelTime.START_NOW, null);
    showResults(travelTime);
  8. 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 getElapsedTime() to retrieve the estimated travel time. Convert the returned travel time from milliseconds to an hour: minute: seconds format. Invoke getDistance() to retrieve the estimated travel distance. Convert the returned distances from meters to kilometers. Invoke setText() to display the results for the travel time and distance.
    private void showResults(final TravelTime travelTime)
    {
        Application.getApplication().invokeLater(new Runnable()
        {
            public void run()
            {
                long value = travelTime.getElapsedTime() / 1000;
                long seconds = value % 60;
                value /= 60;
                long minutes = value % 60;
                long hours = value / 60;
    
                StringBuffer buffer = new StringBuffer();
                buffer.append(hours);
                buffer.append(':');
                if (minutes < 10)
                {
                    buffer.append('0');
                }
                buffer.append(minutes);
                buffer.append(':');
                if (seconds < 10)
                {
                    buffer.append('0');
                }
                buffer.append(seconds);
    
                String msg = "Travel Time (h:m:s): " + buffer.toString();
                TravelTimeScreen.this._timeLabel.setText(msg);
    
                double distance = travelTime.getDistance() / 1000.0;
                msg = "Distance (km): " + Double.toString(distance);
                TravelTimeScreen.this._distanceLabel.setText(msg);
            }
        });
    }

Was this information helpful? Send us your comments.