Top Banner
BlackBerry Java SDK Location-Based Services Version: 6.0 Development Guide
122

BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Oct 23, 2014

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

BlackBerry Java SDKLocation-Based ServicesVersion: 6.0

Development Guide

Page 2: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Published: 2010-09-03SWD-1239071-0903111352-001

Page 3: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Contents1 Location-based services overview............................................................................................................................................. 4

2 GPS overview................................................................................................................................................................................ 5

Turning on and querying Location Services on the device........................................................................................................ 6

Querying location sources............................................................................................................................................................. 7

Specifying the GPS mode.............................................................................................................................................................. 8

GPS modes.............................................................................................................................................................................. 8

Specifying the GPS mode by using JSR 179................................................................................................................................. 9

Specify the GPS mode (JSR 179)........................................................................................................................................... 9

Criteria mapping properties.................................................................................................................................................. 10

Specifying the GPS mode by using BlackBerry extensions to JSR 179..................................................................................... 11

Specify the GPS mode by using BlackBerry extensions to JSR 179.................................................................................. 12

Retrieving location information by using the assisted GPS mode............................................................................................ 13

Assisted mode using a PDE server....................................................................................................................................... 13

Verify that PDE server information is required................................................................................................................... 13

Specify the PDE server information..................................................................................................................................... 14

Code sample: Specifying the PDE server information....................................................................................................... 15

Retrieving a location provider....................................................................................................................................................... 16

Retrieve a location provider by using the LocationProvider class.................................................................................... 17

Controlling location tracking by using the BlackBerryLocationProvider class................................................................ 19

Control location tracking by using the BlackBerryLocationProvider class...................................................................... 19

Code sample: Using the BlackBerryLocationProvider class to control location tracking.............................................. 21

Retrieve a location provider by using the BlackBerryLocationProvider class.................................................................. 23

Retrieving the location of a BlackBerry device............................................................................................................................ 24

Retrieve the location of a BlackBerry device....................................................................................................................... 24

Code sample: Retrieving the GPS location of a BlackBerry device.................................................................................. 25

Retrieve the location of a BlackBerry device by specifying continuous fix requests...................................................... 26

Code sample: Retrieving the GPS location of a BlackBerry device by using continuous fix requests......................... 27

Retrieving location information by using the Location class............................................................................................ 28

Retrieve location information by using the Location class................................................................................................ 29

Code sample: Using the Location class to retrieve GPS location information............................................................... 30

Retrieving location information by using the BlackBerryLocation class.......................................................................... 32

Retrieve satellite information by using the BlackBerryLocation class............................................................................. 32

Code sample: Using the BlackBerryLocation class to retrieve satellite information..................................................... 34

Page 4: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Change the criteria to receive location information.......................................................................................................... 35

Code sample: Changing the criteria to retrieve location information............................................................................. 37

Error handling.................................................................................................................................................................................. 39

Handle errors (JSR 179)......................................................................................................................................................... 39

Handle errors (BlackBerry extensions to JSR 179).............................................................................................................. 40

Retrieve a GPS location by using a web page............................................................................................................................. 42

Retrieving a GPS location by using a web page................................................................................................................. 44

3 Geolocation overview.................................................................................................................................................................. 46

Geolocation modes......................................................................................................................................................................... 46

Retrieving the location of a device by using the geolocation service....................................................................................... 47

Retrieve the location of a device by using the geolocation service.................................................................................. 47

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

Retrieving the optimal fix with GPS and geolocation................................................................................................................. 54

Retrieve the optimal single fix.............................................................................................................................................. 54

Code sample: Retrieving the optimal single fix.................................................................................................................. 58

Retrieve optimal multiple fixes............................................................................................................................................. 61

Code sample: Retrieving optimal multiple fixes................................................................................................................. 65

Requesting concurrent GPS and geolocation updates.............................................................................................................. 68

4 Geocoding and reverse geocoding........................................................................................................................................... 69

Retrieve geospatial coordinates for an address by using geocoding....................................................................................... 69

Retrieve an address by using reverse geocoding........................................................................................................................ 71

Code sample: Retrieving an address by using geospatial coordinates and reverse geocoding............................................ 73

5 BlackBerry Maps.......................................................................................................................................................................... 74

Opening BlackBerry Maps from your application....................................................................................................................... 74

Open BlackBerry Maps by using the default settings................................................................................................................ 74

Open BlackBerry Maps by using information from a contact................................................................................................... 75

Open BlackBerry Maps by using specific coordinates................................................................................................................ 77

Open BlackBerry Maps by using a landmark............................................................................................................................... 78

Opening BlackBerry Maps by using a location document......................................................................................................... 80

XML element: <lbs>................................................................................................................................................................ 80

XML element: <location>....................................................................................................................................................... 81

XML element: <getRoute>..................................................................................................................................................... 83

Display and clear locations on a map by using a location document.............................................................................. 83

Page 5: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Display and clear a route on a map by using a location document................................................................................. 85

Open BlackBerry Maps by using a local search.......................................................................................................................... 87

Using KML documents with BlackBerry Maps............................................................................................................................ 88

Supported KML elements...................................................................................................................................................... 88

Create a basic KML document.............................................................................................................................................. 89

Displaying KML overlays on BlackBerry Maps.................................................................................................................... 89

Invoke BlackBerry Maps by using a KML document.......................................................................................................... 90

Opening BlackBerry Maps from the BlackBerry Browser........................................................................................................... 91

6 Custom maps................................................................................................................................................................................ 92

Adding a map to an application.................................................................................................................................................... 92

Add a map to an application................................................................................................................................................. 93

Code sample: Adding a map to an application................................................................................................................... 95

Specifying locations on a map....................................................................................................................................................... 95

Tagging and setting the visibility for locations on a map.......................................................................................................... 96

Tag and set the visibility for locations on a map................................................................................................................ 97

Code sample: Tagging and setting the visibility for locations on a map......................................................................... 99

Creating a static image of a map.................................................................................................................................................. 101

Adding fields on top of a map....................................................................................................................................................... 102

Displaying KML overlays on a map............................................................................................................................................... 103

7 Navigation.................................................................................................................................................................................... 105

Retrieving the estimated travel time and distance..................................................................................................................... 105

Retrieve the estimated travel time and distance................................................................................................................ 105

Code sample: Retrieving the estimated travel time and distance.................................................................................... 109

8 Find more information................................................................................................................................................................ 113

9 Glossary......................................................................................................................................................................................... 114

10 Provide feedback......................................................................................................................................................................... 115

11 Document revision history......................................................................................................................................................... 116

12 Legal notice.................................................................................................................................................................................. 118

Page 6: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Location-based services overview 1

You can create location and maps-based applications for BlackBerry® devices by using the Location-Based Services APIs thatthe BlackBerry® Java® SDK provides. You can use these APIs to retrieve the location of a BlackBerry device, display locationinformation in a map, and navigate to a location.

You can retrieve location information for a device by using one of the following services:

• GPS: Provides location information by using GPS satellites• Geolocation: Provides an approximate location by using cell tower positioning and WLAN access points• Geocoding and reverse geocoding: Provides geospatial coordinates for a street address (geocoding), and provides a street

address for geospatial coordinates (reverse geocoding)

To display location information, you can choose to integrate your application with BlackBerry® Maps or you can embed and builda custom mapping application by using the Maps API that is provided in the net.rim.blackberry.api.maps package.You can use the Maps API to embed a map in an application, add data to a map, display KML overlays, and create static imagesof a map.

To provide navigation information, such as the estimated time of arrival, you can use the Travel Time API that is provided in thenet.rim.device.api.lbs.travel package. The Travel Time API uses current and historical traffic data to provide anestimate for the total travel time and distance for automobile travel to destinations in the United States and Canada.

Development Guide Location-based services overview

4

Page 7: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

GPS overview 2

You can allow a BlackBerry® device application to retrieve the GPS location of a BlackBerry device. The values for the locationinformation are returned as the coordinates for latitude, longitude, and altitude.

The GPS mode that you specify to retrieve the location information depends on the type of application that you want to develop.The GPS modes include the autonomous mode, assisted mode, and cell site mode. The GPS mode can affect the initial speed ofa GPS fix and the level of location accuracy. For example, a weather application might specify a cell site mode, which can quicklyprovide an approximate location. For more information about the BlackBerry device models and their available correspondingGPS modes, visit http://www.blackberry.com/knowledgecenterpublic/ to read article DB-00615.

To retrieve location information, you can use the JSR 179 Location API for Java® ME in thejavax.microedition.location package, or the BlackBerry extension to JSR 179 in thenet.rim.device.api.gps package.

The JSR 179 Location API for Java MEis supported on BlackBerry devices that run BlackBerry® Device Software 4.0.2 or later.

The BlackBerry extensions to JSR 179 is supported on BlackBerry devices that run BlackBerry Device Software 5.0.0 or later.

Retrieving the GPS location of a BlackBerry device involves the following actions:

• Specifying the GPS mode• Retrieving a location provider• Making a GPS request that is based on the frequency of the GPS fix• Retrieving the GPS location of a BlackBerry device

Code sample: Specifying the GPS mode/* JSR 179 */Criteria myCriteria = new Criteria();

/* JSR 179 extension */BlackBerryCriteria myBlackBerryCriteria = new BlackBerryCriteria(…);

Code sample: Retrieving a location provider/* JSR 179 */LocationProvider myProvider = LocationProvider.getInstance(myCriteria);

/* JSR 179 extension */BlackBerryLocationProvider myBlackBerryProvider = (BlackBerryLocationProvider) LocationProvider.getInstance(myBlackBerryCriteria);

Code sample: Making a GPS request that is based on the frequency of the GPS fix/* * Single GPS fix *//* JSR 179 */

Development Guide GPS overview

5

Page 8: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Location myLoc = myProvider.getLocation(…);

/* JSR 179 extension */BlackBerryLocation myBlackBerryLoc = myBlackBerryProvider.getLocation(…);

/* * Continuous GPS fixes *//* JSR 179 */myProvider.setLocationListener(…);

/* JSR 179 extension */myBlackBerryProvider.setLocationListener(…);

Code sample: Retrieving the GPS location of a BlackBerry device/* JSR 179 */double lat = myLoc.getQualifiedCoordinates().getLatitude();

/* JSR 179 extension */double lat = myBlackBerryLoc.getQualifiedCoordinates().getLatitude();

Turning on and querying Location Services on the deviceThe Location Services option on the BlackBerry® device controls the availability of location data. When the Location Servicesoption is turned on, you can retrieve location information from any available location source (internal GPS receiver, external GPSreceiver, and geolocation). When the Location Services option is turned off, location information is unavailable.

You can check if the Location Service option is turned on by invoking LocationInfo.isLocationOn(), which is providedin the net.rim.device.api.gps package. If the option is not turned on, you can programmatically turn it on by invokingLocationInfo.setLocationOn(). To turn on the Location Services option, your application must be signed and it musthave permission to change the settings on the device. Make sure your application prompts the BlackBerry device user forpermission to turn on location services.

When you invoke setLocationOn(), the following actions take place:

• If the Location Services option is turned off , the option is turned on, and location data from GPS becomes available, if thedevice supports GPS technology and the IT policy on the BlackBerry® Enterprise Server permits access to the GPS feature

• Location data from the geolocation service becomes available, if the Location Data option on the BlackBerry device isenabled, the IT policy on the BlackBerry Enterprise Server permits access to the geolocation service, and the wireless serviceprovider permits access to the service

• For external GPS receivers, location data becomes available if the external receiver is specified as the current GPS DataSource (in the Options on the device)

Note: You cannot programmatically turn off the Location Services option. The option can be turned off only by the user.

Development Guide Turning on and querying Location Services on the device

6

Page 9: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Querying location sourcesLocation data can be retrieved by using various location sources, such as an internal GPS receiver, an external GPS receiver, ora geolocation service. Before retrieving location data, you should verify which location sources the BlackBerry® device supports,and whether the location source is available. A location source may be unsupported for the following reasons:

• The location source is not supported by the device hardware.• The location source is turned off by the wireless service provider (no service book present).• If the mobile network connection is turned off, the location source for cell site geolocation is not supported but the location

source for GPS is supported, however, the time to the first fix may be slow.• If the Wi-Fi® connection is turned off, the location source for geolocation by using WLAN access points is not supported.• If there is insufficient network connectivity, the geolocation location source is not supported.

A location source is available if all the settings are turned on for the source. However, a location source might be supported butmight be unavailable on the device (for example, the BlackBerry device user turned off the location source).

The location sources are defined as constants in the GPSInfo and LocationInfo classes. The constants can be one of thefollowing values:

• GPSInfo.GPS_DEVICE_INTERNAL• GPSInfo.GPS_DEVICE_BLUETOOTH• LocationInfo.LOCATION_SOURCE_GEOLOCATION• LocationInfo.LOCATION_SOURCE_GEOLOCATION_CELL• LocationInfo.LOCATION_SOURCE_GEOLOCATION_WLAN

You can query location sources by using the following methods that are defined in thenet.rim.device.api.gps.LocationInfo class:

Method Description

getSupportedLocationSources() This method returns an integer mask that represents the location

sources that the device supports.

isLocationSourceSupported(int mode) This method returns a value of true if the source you specify is

supported on the device.

getAvailableLocationSources() This method returns an integer mask that represents the location

sources that the device supports. A location source is available if it is

supported and enabled for use.

isLocationSourceAvailable(int mode) This method returns a value of true if the mode you specify is

available to provide location information.

Development Guide Querying location sources

7

Page 10: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Code sample: Verifying whether location sources are supportedint locationCapability = LocationInfo.getSupportedLocationSources();boolean gps = (locationCapability & (GPSInfo.GPS_DEVICE_INTERNAL | GPSInfo.GPS_DEVICE_BLUETOOTH)) != 0

Code sample: Verifying whether any location sources are availableif (LocationInfo.getAvailableLocationSources() != 0)

Specifying the GPS modeYou must specify the GPS mode to retrieve the location of a BlackBerry® device. GPS modes include autonomous, assisted andcell site.

• Autonomous mode relies on GPS satellites only.• Assisted mode relies on GPS satellites and servers on the wireless network.• Cell site mode relies on the geolocation service, or the wireless network to provide the location information of the current

base station.

GPS modesYour BlackBerry® device application must verify that a GPS mode is available for use on each BlackBerry device that yourapplication runs on, before your application can use the GPS mode.

GPS mode Description

cell site This mode uses the wireless network to achieve the first GPS fix, and is generally considered the

fastest mode. This mode does not provide BlackBerry device tracking information such as the speed

and the bearing.

autonomous This mode uses the GPS receiver on the BlackBerry device to retrieve location information. This mode

cannot be used indoors or in close proximity to many physical obstructions, and it can take several

minutes to fully synchronize with four or more satellites for the first GPS fix.

assisted This mode uses the wireless network to retrieve satellite information. This mode can achieve a fast

retrieval of the first GPS fix.

MS-based This mode uses the wireless network to retrieve satellite information. After the first GPS fix, the

BlackBerry device relies on the autonomous mode to more accurately retrieve subsequent GPS fixes.

The MS-based GPS mode applies to BlackBerry devices that use the Qualcomm® gpsOne® and

operate on the CDMA network.

Development Guide Specifying the GPS mode

8

Page 11: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

GPS mode Description

MS-assisted This mode uses the wireless network to retrieve satellite information. This mode applies to BlackBerry

devices that use the Qualcomm gpsOne and operate on the CDMA network.

speed optimal This mode focuses on providing the fastest possible GPS fix that meets the criteria that is set by the

application. This mode applies to BlackBerry devices that use the Qualcomm gpsOne and operate

on the CDMA network.

accuracy optimal This mode is determined based on the accuracy of a GPS fix. This mode either relies on network

information, or performs local calculations, depending on what is the most accurate and available.

This mode applies to BlackBerry devices that use the Qualcomm gpsOne and operate on the CDMA

network.

data optimal This mode is determined based on the least amount of network traffic that is required for a GPS fix.

This mode either relies on network information, or performs local calculations, depending on what

is available that uses the least amount of data traffic. This mode applies to BlackBerry devices that

use the Qualcomm gpsOne and operate on the CDMA network.

Bluetooth® enabled

GPS

This mode is determined by the configuration of the Bluetooth enabled GPS device. The configuration

of a Bluetooth enabled GPS device that is paired with a BlackBerry device cannot be specified in a

Criteria object.

Specifying the GPS mode by using JSR 179If you use the JSR 179 package, you must specify the properties for the GPS mode in thejavax.microedition.location.Criteria class. The application cannot set the GPS mode directly. If a BlackBerry®device is paired with a Bluetooth® enabled GPS device to determine location, then the Bluetooth enabled device will be usedregardless of how the Criteria object has been configured.

Specify the GPS mode (JSR 179)The JSR 179 Location API is supported on BlackBerry® devices that run BlackBerry® Device Software 4.0.2 or later.

1. Import the required class.

import javax.microedition.location.Criteria;

2. Create a class and constructor.

public class handleGPS{ public handleGPS()

Development Guide Specifying the GPS mode by using JSR 179

9

Page 12: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

{ }}

3. In the constructor, create an instance of the Criteria class. Create a variable to specify a GPS mode.

Criteria myCriteria = new Criteria();int myMode = 2; // AUTONOMOUS

4. In the constructor, map the properties for each GPS mode by invoking the corresponding set method for each property.

switch ( myMode ){ case 0: // CELLSITE myCriteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_LOW); myCriteria.setHorizontalAccuracy(Criteria.NO_REQUIREMENT); myCriteria.setVerticalAccuracy(Criteria.NO_REQUIREMENT); myCriteria.setCostAllowed(true); break;

case 1: // ASSIST myCriteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_MEDIUM); myCriteria.setHorizontalAccuracy(100); myCriteria.setVerticalAccuracy(100); myCriteria.setCostAllowed(true); break;

case 2: // AUTONOMOUS myCriteria.setCostAllowed(false); break;}

Criteria mapping propertiesIf you use the JSR 179 Location API for to specify a GPS mode, you must map the following properties for the Criteria class.

GPS modeHorizontal

accuracy

Vertical

accuracyCost allowed

Power usage

levelResponse time Fix frequency

Autonomous required required no any any single or

multiple

Autonomous not required not required no medium, high,

or not required

any single or

multiple

Assisted or

data optimal

not required not required yes medium, high,

or not required

any single or

multiple

Development Guide Specifying the GPS mode by using JSR 179

10

Page 13: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

GPS modeHorizontal

accuracy

Vertical

accuracyCost allowed

Power usage

levelResponse time Fix frequency

Assisted or

speed optimal

required required yes high quality of

service

multiple

Assisted or MS-

Based

required required yes medium or not

required

quality of

service

multiple

Assisted or

accuracy

optimal

required required yes high quality of

service

single

Assisted or MS-

Assisted

required required yes medium or not

required

quality of

service

single

Cell site not required not required yes low any any

Specifying the GPS mode by using BlackBerry extensions to JSR 179The BlackBerry® extensions to JSR 179 provide an enhanced set of GPS criteria. Thenet.rim.device.api.gps.BlackBerryCriteria class extends thejavax.microedition.location.Criteria class. You can use the methods in the BlackBerryCriteria class tospecify the GPS requirements for your application.

Method Description

setMode (int) You can use this method to specify an initial GPS mode when you create a

BlackBerryCriteria object.

setFailoverMode (int, int, int) You can use this method to specify a GPS failover mode to use when the initial

GPS mode is unsuccessful. This method applies only to the internal GPS

functionality on a BlackBerry device.

setSubsequentMode (int) You can use this method to specify a subsequent GPS mode to use after a

successful first GPS fix is retrieved.

setGPSRestartInterval (int,

int)

You can use this method to specify an interval to wait before automatically

restarting the GPS retrieval process when a GPS fix is not successfully retrieved.

You can specify intervals to a maximum of 15 minutes and a minimum of 2 seconds,

with a limit of three automatic retries.

Development Guide Specifying the GPS mode by using BlackBerry extensions to JSR 179

11

Page 14: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Method Description

setSatelliteInfoRequired

(boolean, boolean)

You can use this method to specify whether you want satellite tracking

information. The satellite tracking information consists of the number of satellites

in view, and their IDs, signal quality, elevation, and azimuth. This applies only to

the internal GPS functionality on a BlackBerry device.

Specify the GPS mode by using BlackBerry extensions to JSR 179The BlackBerry® extensions to JSR 179 are supported on BlackBerry devices that run BlackBerry® Device Software 5.0.0 or later.

1. Import the required class.

import net.rim.device.api.gps.*;

2. Create a class and constructor.

public class handleGPS{ BlackBerryCriteria myCriteria;

public handleGPS() { }}

3. In the constructor, create a try/catch block. In this block, create an instance of the BlackBerryCriteria class bypassing the GPS mode as a parameter to the constructor.

try{ myCriteria = new BlackBerryCriteria(GPSInfo.GPS_MODE_ASSIST);}catch ( UnsupportedOperationException ex ){ return;}

4. In the constructor, invoke setFailloverMode() to specify the GPS failover mode to use if the first GPS mode that youspecify cannot retrieve a GPS fix. Invoke setSubsequentMode() to specify a subsequent GPS mode to use after asuccessful first fix is retrieved.

myCriteria.setFailoverMode(GPSInfo.GPS_MODE_AUTONOMOUS, 3, 100);myCriteria.setSubsequentMode(GPSInfo.GPS_MODE_AUTONOMOUS);

5. To verify if a GPS mode is supported, invoke GPSInfo.isGPSModeAvailable() and pass the GPS mode as aparameter. Invoke setMode() to specify the GPS mode, if the mode is supported.

Development Guide Specifying the GPS mode by using BlackBerry extensions to JSR 179

12

Page 15: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

public class handleGPS{ public handleGPS() { BlackBerryCriteria myCriteria = new BlackBerryCriteria();

if (GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_ASSIST)) myCriteria.setMode(GPSInfo.GPS_MODE_ASSIST); else if (GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_AUTONOMOUS)) myCriteria.setMode(GPSInfo.GPS_MODE_AUTONOMOUS); }}

Retrieving location information by using the assisted GPS mode

Assisted mode using a PDE server

The assisted mode can be used with BlackBerry® devices that are associated with a CDMA network that utilizes PDE servertechnology. The assisted mode is designed to provide fast retrieval of a GPS fix.

Assisted GPS capabilities are currently defined by wireless service providers. In many instances, you must enter into a formalrelationship with wireless service providers before you can connect to their PDE server.

Verify that PDE server information is requiredBefore using assisted mode with a PDE server, you must verify whether PDE server information is required.

1. Import the required class.

import net.rim.device.api.gps.GPSSettings;

2. Create a class and constructor. In the constructor, invoke isPDEInfoRequired() to verify if you need to specify thePDE server information to use assisted mode.

public class checkPDE{ public checkPDE() { if ( isPDEInfoRequired(GPSInfo.GPS_MODE_ASSIST)) { // set up PDE server access } }}

Development Guide Retrieving location information by using the assisted GPS mode

13

Page 16: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Specify the PDE server information

Before you begin:

You must have the user ID, password, IP address and port number that the wireless service provider uses for their PDE server.

1. Import the required classes.

import net.rim.device.api.gps.*;import javax.microedition.location.*;

2. Create a class and a constructor.

public class handleGPS{ static GPSThread gpsThread;

public handleGPS() { }}

3. In the constructor, create and start an instance of the Thread class.

gpsThread = new GPSThread();gpsThread.start();

4. 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() { }}

5. In the run() method of the private class, invoke isGPSModeAvailable() passing GPS_MODE_ASSIST as aparameter to determine if the assisted mode is available on the BlackBerry® device. Invoke isPDEInfoRequired() todetermine if you need to specify PDE server information. If PDE server information is required, create an instance of theBlackBerryCriteria class by passing GPS_MODE_ASSIST as a parameter to the constructor.

if ( !GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_ASSIST) || !GPSSettings.isPDEInfoRequired(GPSInfo.GPS_MODE_ASSIST)) return;

BlackBerryCriteria myCriteria = new BlackBerryCriteria (GPSInfo.GPS_MODE_ASSIST);

Development Guide Retrieving location information by using the assisted GPS mode

14

Page 17: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

6. In the run() method of the private class, create a try/catch block. In the block, associate an instance of theBlackBerryCriteria class with a BlackBerryLocationProvider object. Create and specify the user ID,password, and IP address String objects, and the port ID. Combine the String objects into a single String. InvokesetPDEInfo()to specify the PDE server IP address and port number of the BlackBerry device.

try{ BlackBerryLocationProvider myProvider = (BlackBerryLocationProvider) LocationProvider.getInstance(myCriteria); String user = "UserID"; String pass = "Password"; String ip = "127.0.0.1"; int port = 0; String str = ip + ";" + user + ";" + pass; GPSSettings.setPDEInfo(str, port);

try { BlackBerryLocation myLocation = (BlackBerryLocation)myProvider.getLocation(10); } catch ( InterruptedException iex ) {} catch ( LocationException lex ) {}}catch ( LocationException lex ){}

return;

Code sample: Specifying the PDE server information

import net.rim.device.api.gps.*;import javax.microedition.location.*;

public class handleGPS{ static GPSThread gpsThread;

public handleGPS() { gpsThread = new GPSThread(); gpsThread.start(); }

private static class GPSThread extends Thread {

Development Guide Retrieving location information by using the assisted GPS mode

15

Page 18: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

public void run() { if ( !GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_ASSIST) || !GPSSettings.isPDEInfoRequired(GPSInfo.GPS_MODE_ASSIST)) return;

BlackBerryCriteria myCriteria = new BlackBerryCriteria(GPSInfo.GPS_MODE_ASSIST);

try { BlackBerryLocationProvider myProvider = (BlackBerryLocationProvider) LocationProvider.getInstance(myCriteria); String user = "UserID"; String pass = "Password"; String ip = "127.0.0.1"; int port = 0; String str = ip + ";" + user + ";" + pass; GPSSettings.setPDEInfo(str, port);

try { BlackBerryLocation myLocation = (BlackBerryLocation)myProvider.getLocation(10); } catch ( InterruptedException iex ) { return; } catch ( LocationException lex ) { return; } } catch ( LocationException lex ) { return; } return; } }}

Retrieving a location providerAfter you specify the GPS mode, you must retrieve the location provider that your application uses to support the GPS mode. Alocation provider represents the source of the location information and it works based on given criteria (for example, the horizontalaccuracy and the power usage) .

Development Guide Retrieving a location provider

16

Page 19: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

If the application uses the Criteria class from the JSR 179 package to specify a GPS mode, then the application must retrievean instance of the LocationProvider class. If the application uses the BlackBerryCriteria class, then the applicationmust retrieve an instance of the BlackBerryLocationProvider class.

A BlackBerryLocationProvider object extends the javax.microedition.location.LocationProviderclass. You can use BlackBerryLocationProvider to perform the following actions:

• Process a location request that you specify in the net.rim.device.api.gps.BlackBerryCriteria object.• Pause and resume the location listener.• Retrieve the GPS receiver type including an internal or a Bluetooth®enabled GPS receiver.

When the location listener is in a paused state, the application does not receive GPS fixes. The location listener can be in a readystate while also in a paused state.

Retrieve a location provider by using the LocationProvider class1. Import the required classes.

import javax.microedition.location.*;

2. Create a class and a constructor.

public class handleGPS{ public handleGPS() { }}

3. In the constructor, create an instance of the Criteria class.

Criteria myCriteria = new Criteria();

4. In the constructor, configure the Criteria object to use the specified GPS mode. In the following code sample, autonomousmode is specified by invoking setCostAllowed(false).

int myMode = 2; // AUTONOMOUS

switch ( myMode ){ case 0: // CELLSITE myCriteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_LOW); myCriteria.setHorizontalAccuracy(Criteria.NO_REQUIREMENT); myCriteria.setVerticalAccuracy(Criteria.NO_REQUIREMENT); myCriteria.setCostAllowed(true); break;

case 1: // ASSIST myCriteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_MEDIUM); myCriteria.setHorizontalAccuracy(100);

Development Guide Retrieving a location provider

17

Page 20: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

myCriteria.setVerticalAccuracy(100); myCriteria.setCostAllowed(true); break;

case 2: // AUTONOMOUS myCriteria.setCostAllowed(false); break;}

5. In the constructor, create a try/catch block. Within the block, create a LocationProvider object by invokinggetInstance().

try{ LocationProvider myProvider = LocationProvider.getInstance(myCriteria);}catch ( LocationException lex ){ return;}

Code sample: Retrieving a location provider by using the LocationProvider classimport javax.microedition.location.*;

public class handleGPS{ public handleGPS() { Criteria myCriteria = new Criteria();

int myMode = 2; // AUTONOMOUS

switch ( myMode ) { case 0: // CELLSITE myCriteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_LOW); myCriteria.setHorizontalAccuracy(Criteria.NO_REQUIREMENT); myCriteria.setVerticalAccuracy(Criteria.NO_REQUIREMENT); myCriteria.setCostAllowed(true); break;

case 1: // ASSIST myCriteria.setPreferredPowerConsumption(Criteria .POWER_USAGE_MEDIUM); myCriteria.setHorizontalAccuracy(100); myCriteria.setVerticalAccuracy(100); myCriteria.setCostAllowed(true); break;

case 2: // AUTONOMOUS

Development Guide Retrieving a location provider

18

Page 21: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

myCriteria.setCostAllowed(false); break; }

try { LocationProvider myProvider = LocationProvider.getInstance(myCriteria); } catch ( LocationException lex ) { return; } }}

Controlling location tracking by using the BlackBerryLocationProvider class

The net.rim.device.api.gps.BlackBerryLocationProvider class extends thejavax.microedition.location.LocationProvider class and it is required for BlackBerry® device applications thatuse the BlackBerry extensions to JSR 179. You can use the methods that are provided in theBlackBerryLocationProvider class to control location tracking.

Method Description

getProviderType() This method retrieves the source of the location information. The source is either an

internal or external GPS receiver.

pauseLocationTracking (int

interval)

This method pauses location tracking and stops receiving GPS fixes. You can pass

an interval parameter, specified in seconds, to make sure that the GPS receiver

remains active during the pause interval. You can pass an interval of 0 to indefinitely

stop location tracking and make the GPS receiver inactive.

resumeLocationTracking() This method resumes location tracking after it is in a paused state.

stopLocationTracking() This method stops location tracking only if tracking was previously started. Your

application must invoke BlackBerryLocationProvider.reset() before it

restarts location tracking by using the same location provider.

Control location tracking by using the BlackBerryLocationProvider classYou can pause, resume, and stop location tracking by using thenet.rim.device.api.gps.BlackBerryLocationProvider class.

1. Import the required classes.

Development Guide Retrieving a location provider

19

Page 22: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

import net.rim.device.api.gps.*;import javax.microedition.location.*;

2. Create a new class and a constructor.

public class handleGPS{ static BlackBerryLocationProvider myProvider;

public handleGPS() { }}

3. In the constructor, create a try/catch block. In the block, create an instance of the BlackBerryCriteria class bypassing the GPS mode as a parameter to the constructor.

try{ BlackBerryCriteria myCriteria = new BlackBerryCriteria(GPSInfo.GPS_MODE_AUTONOMOUS);}catch ( UnsupportedOperationException uoex ){ return;}

4. In the try part of the block, create a new try/catch block. In this block, create an instance of theBlackBerryLocationProvider class by retrieving an instance of the BlackBerryCriteria class. InvokesetLocationListener() by passing the interval value, timeout value, and maximum age as parameters to add aLocationListener.

try{ myProvider = (BlackBerryLocationProvider) LocationProvider.getInstance(myCriteria); myProvider.setLocationListener(new handleGPSListener(), 10, -1, -1);}catch ( LocationException lex ){ return;}

myProvider.pauseLocationTracking(30);myProvider.resumeLocationTracking();myProvider.stopLocationTracking();

5. Outside of the try/catch block, invoke pauseLocationTracking(), resumeLocationTracking(), orstopLocationTracking() to pause, resume, or stop location tracking.

Development Guide Retrieving a location provider

20

Page 23: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

myProvider.pauseLocationTracking(30);myProvider.resumeLocationTracking();myProvider.stopLocationTracking();

6. In the class, implement the LocationListener interface. Implement the basic framework for the locationUpdated() method, and the providerStateChanged() method.

public static class handleGPSListener implements LocationListener{ public void locationUpdated(LocationProvider provider, Location location) { if (location.isValid()) {} else {} }

public void providerStateChanged(LocationProvider provider, int newState) { if (newState == LocationProvider.AVAILABLE) {} else if (newState == LocationProvider.OUT_OF_SERVICE) {} else if (newState == LocationProvider.TEMPORARILY_UNAVAILABLE ) {} }}

Code sample: Using the BlackBerryLocationProvider class to control location tracking

import net.rim.device.api.gps.*;import javax.microedition.location.*;

public class handleGPS{ static BlackBerryLocationProvider myProvider;

public handleGPS() { try { BlackBerryCriteria myCriteria = new BlackBerryCriteria(GPSInfo.GPS_MODE_AUTONOMOUS);

try { myProvider = (BlackBerryLocationProvider) LocationProvider.getInstance(myCriteria); myProvider.setLocationListener(new handleGPSListener(), 10, -1, -1); }

Development Guide Retrieving a location provider

21

Page 24: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

catch ( LocationException lex ) { return; }

myProvider.pauseLocationTracking(30); myProvider.resumeLocationTracking(); myProvider.stopLocationTracking(); } catch ( UnsupportedOperationException uoex ) { return; }

return; }

public static class handleGPSListener implements LocationListener { public void locationUpdated(LocationProvider provider, Location location) { if (location.isValid()) { // do something } else { // invalid location } }

public void providerStateChanged(LocationProvider provider, int newState) { if (newState == LocationProvider.AVAILABLE) { // available } else if (newState == LocationProvider.OUT_OF_SERVICE) { // GPS unavailable due to IT policy specification } else if (newState == LocationProvider.TEMPORARILY_UNAVAILABLE ) { // no GPS fix } } }}

Development Guide Retrieving a location provider

22

Page 25: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Retrieve a location provider by using the BlackBerryLocationProvider class1. Import the required classes.

import net.rim.device.api.gps.*;import javax.microedition.location.*;

2. Create a class and a constructor.

public class handleGPS{ static BlackBerryCriteria myCriteria;

public handleGPS() { }}

3. In the constructor, create a try/catch block. In the block, create an instance of the BlackBerryCriteria class andpass the GPS mode to the constructor. Create a second try/catch block, then create an instance of theBlackBerryLocationProvider class by invoking getInstance() to retrieve an instance of theBlackBerryCriteria object.

try { myCriteria = new BlackBerryCriteria(GPSInfo.GPS_MODE_ASSIST);

try { BlackBerryLocationProvider myProvider = (BlackBerryLocationProvider) LocationProvider.getInstance(myCriteria); } catch ( LocationException lex ) { return; } } catch ( UnsupportedOperationException ex ) { return; } }}

Development Guide

23

Page 26: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Retrieving the location of a BlackBerry deviceYou can retrieve the location of a BlackBerry® device by specifying a single GPS fix, or by specifying a location listener to retrievecontinuous GPS fixes.

Retrieve the location of a BlackBerry device1. Import the required classes.

import javax.microedition.location.*;

2. Create a class and a constructor.

public class handleGPS{ public handleGPS() { }}

3. Declare static fields in the class.

static GPSThread gpsThread;static double latitude;static double longitude;

4. In the constructor, create and start a local thread.

gpsThread = new GPSThread();gpsThread.start();

5. In the class, create a private class that extends Thread, and create a run() method.

private class GPSThread extends Thread{ public void run() { }}

6. In the run() method, create an instance of the Criteria class. Invoke setCostAllowed(false) to specify thatthe autonomous mode.

Criteria myCriteria = new Criteria();myCriteria.setCostAllowed(false);

Development Guide Retrieving the location of a BlackBerry device

24

Page 27: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

7. In the run() method, create a try/catch block. In the block create a LocationProvider object by getting aninstance of the Criteria object. Create another try/catch block to create a Location object to request the currentlocation of the BlackBerry® device and specify the timeout period in seconds. When the getLocation() method returns,request the latitude and longitude coordinates.

try{ LocationProvider myLocationProvider = LocationProvider.getInstance(myCriteria);

try { Location myLocation = myLocationProvider.getLocation(300); latitude = myLocation.getQualifiedCoordinates().getLatitude(); longitude = myLocation.getQualifiedCoordinates().getLongitude(); } catch ( InterruptedException iex ) { return; } catch ( LocationException lex ) { return; }}catch ( LocationException lex ){ return;}return;

Code sample: Retrieving the GPS location of a BlackBerry device

import javax.microedition.location.*;

public class handleGPS{ static GPSThread gpsThread; static double latitude; static double longitude;

public handleGPS() { gpsThread = new GPSThread(); gpsThread.start(); }

private static class GPSThread extends Thread {

Development Guide Retrieving the location of a BlackBerry device

25

Page 28: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

public void run() { Criteria myCriteria = new Criteria(); myCriteria.setCostAllowed(false);

try { LocationProvider myLocationProvider = LocationProvider.getInstance(myCriteria);

try { Location myLocation = myLocationProvider.getLocation(300); latitude = myLocation.getQualifiedCoordinates().getLatitude(); longitude = myLocation.getQualifiedCoordinates().getLongitude(); } catch ( InterruptedException iex ) { return; } catch ( LocationException lex ) { return; } } catch ( LocationException lex ) { return; } return; } }}

Retrieve the location of a BlackBerry device by specifying continuous fix requestsYou can use the Location API to retrieve location information of a BlackBerry® device at any interval.

1. Import the required classes and interface.

import javax.microedition.location.*;

2. Create a class and a constructor.

public class handleGPS{ public handleGPS() { }}

Development Guide Retrieving the location of a BlackBerry device

26

Page 29: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

3. In the constructor, create an instance of the Criteria class. Create a try/catch block. In this block, create an instance ofthe LocationProvider class by invoking getInstance() and using the Criteria object. InvokesetLocationListener() to specify the location of the GPS event listener.

Criteria myCriteria = new Criteria();

try{ LocationProvider provider = LocationProvider.getInstance(myCriteria); provider.setLocationListener(new handleGPSListener(), 10, -1, -1);}catch ( LocationException lex ){ return;}

4. In the class, implement the LocationListener interface. You must add functionality as required to this implementation.

public static class handleGPSListener implements LocationListener{ public void locationUpdated(LocationProvider provider, Location location) { if (location.isValid()) { // do something } else { // invalid locatuon } }

public void providerStateChanged(LocationProvider provider, int newState) { if (newState == LocationProvider.OUT_OF_SERVICE) {} else if (newState == Location.TEMPORARILY_UNAVAILABLE ) {} }}

Code sample: Retrieving the GPS location of a BlackBerry device by using continuous fixrequests

import javax.microedition.location.*;

public class handleGPS{ public handleGPS()

Development Guide Retrieving the location of a BlackBerry device

27

Page 30: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

{ Criteria myCriteria = new Criteria();

try { LocationProvider provider = LocationProvider.getInstance(myCriteria); provider.setLocationListener(new handleGPSListener(), 10, -1, -1); } catch ( LocationException lex ) { return; } }

public static class handleGPSListener implements LocationListener { public void locationUpdated(LocationProvider provider, Location location) { if (location.isValid()) { // do something } else { // invalid location } }

public void providerStateChanged(LocationProvider provider, int newState) { if (newState == LocationProvider.OUT_OF_SERVICE) { // GPS unavailable due to IT policy specification } else if (newState == LocationProvider.TEMPORARILY_UNAVAILABLE ) { // no GPS fix } } }}

Retrieving location information by using the Location class

You can use the JSR 179 Location API, which is provided in the javax.microedition.location.Location package, toretrieve the following information:

• latitude as a double• longitude as a double

Development Guide Retrieving the location of a BlackBerry device

28

Page 31: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

• ground speed of the BlackBerry® device, in meters per second• course of the BlackBerry device, in degrees relative to true north• time stamp of the GPS fix• NMEA sentence that contains the number of satellites that a BlackBerry device tracks

Retrieve location information by using the Location classYou can request a GPS fix and then retrieve the latitude, longitude, velocity, course heading, time stamp, and the number ofsatellites 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 autonomousmode.

Development Guide Retrieving the location of a BlackBerry device

29

Page 32: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

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 aninstance of the Criteria object. Create a try/catch block within this block, and create an instance of the Locationclass to retrieve the current GPS fix including a 300 second timeout expiry. Populate the fields, and specify the number ofsatellites 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;

Code sample: Using the Location class to retrieve GPS location information

import javax.microedition.location.*;

public class handleGPS{ static GPSThread gpsThread; static double latitude; static double longitude; static float heading; static float velocity; static long timeStamp; static String nmeaString;

Development Guide Retrieving the location of a BlackBerry device

30

Page 33: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

public handleGPS() { gpsThread = new GPSThread(); gpsThread.start(); }

private static class GPSThread extends Thread { public void run() { Criteria myCriteria = new Criteria(); myCriteria.setCostAllowed(false);

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 ) { return; } catch ( LocationException lex ) { return; } } catch ( LocationException lex ) { return; }

return; } }}

Development Guide Retrieving the location of a BlackBerry device

31

Page 34: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Retrieving location information by using the BlackBerryLocation class

You can use the BlackBerry® extensions to JSR 179 to retrieve location information about the BlackBerry device. You can use theBlackBerryLocation class to retrieve the following information:

• number of satellites that a BlackBerry device is tracking• details about the satellites that a BlackBerry device is tracking• average signal quality of a satellite• data source that produces the GPS fix (an internal or an external GPS receiver)• GPS mode that provides the location information

Retrieve satellite information by using the BlackBerryLocation classYou can request a GPS fix and then retrieve the current number of satellites in view, tracked satellites, average satellite signalquality, GPS data source (internal or external GPS), and the GPS mode.

1. Import the required classes.

import java.util.*;import java.lang.*;import net.rim.device.api.gps.*;

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 int satCount;static int signalQuality;static int dataSource;static int gpsMode;

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 a run() method.

private static class GPSThread extends Thread{ public void run()

Development Guide Retrieving the location of a BlackBerry device

32

Page 35: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

{ }}

6. In run(), create a try/catch block. In this block, create an instance of the BlackBerryCriteria class that specifiesthe GPS mode. Create a second try/catch block. In this block create an instance of theBlackBerryLocationProvider class by getting an instance of the BlackBerryCriteria object.

try{ BlackBerryCriteria myCriteria = new BlackBerryCriteria(GPSInfo.GPS_MODE_AUTONOMOUS);

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

7. Create a third try/catch block that is in the first try/catch block. Create a BlackBerryLocation object to retrievethe GPS fix including a 300 second timeout expiry. Populate the fields and extract the satellite information into aStringBuffer object.

try{ BlackBerryLocation myLocation = (BlackBerryLocation)myProvider.getLocation(300); satCount= myLocation.getSatelliteCount(); signalQuality = myLocation.getAverageSatelliteSignalQuality(); dataSource = myLocation.getDataSource(); gpsMode = myLocation.getGPSMode();

SatelliteInfo si; StringBuffer sb = new StringBuffer("[Id:SQ:E:A]\n"); String separator = ":";

for (Enumeration e = myLocation.getSatelliteInfo(); e!=null && e.hasMoreElements(); ) { si = (SatelliteInfo)e.nextElement(); sb.append(si.getId() + separator); sb.append(si.getSignalQuality() + separator); sb.append(si.getElevation() + separator); sb.append(si.getAzimuth()); sb.append('\n'); }}catch ( InterruptedException iex ){}catch ( LocationException lex ){}

Development Guide Retrieving the location of a BlackBerry device

33

Page 36: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Code sample: Using the BlackBerryLocation class to retrieve satellite information

import net.rim.device.api.gps.*;import java.util.*;import javax.microedition.location.*;

public class handleGPS{ static GPSThread gpsThread; static int satCount; static int signalQuality; static int dataSource; static int gpsMode;

public handleGPS() { gpsThread = new GPSThread(); gpsThread.start(); }

private static class GPSThread extends Thread { public void run() { try { BlackBerryCriteria myCriteria = new BlackBerryCriteria(GPSInfo.GPS_MODE_AUTONOMOUS);

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

try { BlackBerryLocation myLocation = (BlackBerryLocation)myProvider.getLocation(300);

satCount= myLocation.getSatelliteCount(); signalQuality = myLocation.getAverageSatelliteSignalQuality(); dataSource = myLocation.getDataSource(); gpsMode = myLocation.getGPSMode();

SatelliteInfo si; StringBuffer sb = new StringBuffer("[Id:SQ:E:A]\n"); String separator = ":";

Development Guide Retrieving the location of a BlackBerry device

34

Page 37: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

for (Enumeration e = myLocation.getSatelliteInfo(); e!=null && e.hasMoreElements(); ) { si = (SatelliteInfo)e.nextElement(); sb.append(si.getId() + separator); sb.append(si.getSignalQuality() + separator); sb.append(si.getElevation() + separator); sb.append(si.getAzimuth()); sb.append('\n'); } } catch ( InterruptedException iex ) { return; } catch ( LocationException lex ) { return; } } catch ( LocationException lex ) { return; } } catch ( UnsupportedOperationException uoex ) { return; }

return; } }}

Change the criteria to receive location informationYou can use an instance of the LocationProvider class to automatically change the criteria that is used to track the locationof a BlackBerry® device.

1. Import the required classes and interface.

import net.rim.device.api.gps.GPSInfo;import javax.microedition.location.*;

2. Create a class and constructor.

public class handleGPS{ public handleGPS(int gpsMode)

Development Guide Retrieving the location of a BlackBerry device

35

Page 38: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

{ }}

3. In the class, define static fields for the location provider, latitude, longitude, altitude, speed and course.

static LocationProvider locationProvider;static double lat, lon;static float alt, spd, crs;

4. In the constructor, add a code block to set up a LocationProvider instance to switch to a different method of locationtracking. Invoke reset() on the LocationProvider object, and then set the location listener to null to disable thelistener.

if (locationProvider != null){ locationProvider.reset(); locationProvider.setLocationListener(null, -1, -1, -1);}

5. In the constructor, create and configure a Criteria object based on the GPS mode that is passed as a parameter to theconstructor.

Criteria myCriteria = new Criteria();myCriteria.setPreferredResponseTime(Criteria.NO_REQUIREMENT);myCriteria.setCostAllowed(true);

if ( gpsMode == GPSInfo.GPS_MODE_AUTONOMOUS ){ myCriteria.setCostAllowed(false);}else if ( gpsMode == GPSInfo.GPS_MODE_ASSIST ){ myCriteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_MEDIUM);}else{ myCriteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_LOW);}

6. In the constructor, create a try/catch block. In this block, create an instance of the LocationListener class byinvoking getInstance() and passing the Criteria object as a parameter. Specify a location listener to handle theGPS location updates.

try{ locationProvider = LocationProvider.getInstance(myCriteria);

if (locationProvider != null) { locationProvider.setLocationListener (new myLocationListener(), -1, -1, -1);

Development Guide Retrieving the location of a BlackBerry device

36

Page 39: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

}}catch (Exception err){}

7. In the class, create a private static class that implements the LocationListener interface. Retrieve the current locationinformation in the locationUpdated() method. Create a basic implementation of the providerStateChanged() method to monitor the LocationProvider state.

private static class myLocationListener implements LocationListener{ public void locationUpdated(LocationProvider provider, Location location) { lat = location.getQualifiedCoordinates().getLatitude(); lon = location.getQualifiedCoordinates().getLongitude(); alt = location.getQualifiedCoordinates().getAltitude(); spd = location.getSpeed(); crs = location.getCourse(); }

public void providerStateChanged(LocationProvider provider, int newState) {}}

Code sample: Changing the criteria to retrieve location information

import net.rim.device.api.gps.GPSInfo;import javax.microedition.location.*;

public class handleGPS{ static LocationProvider locationProvider; static double lat, lon; static float alt, spd, crs;

public static void main(String[] args) { }

public handleGPS(int gpsMode) { if (locationProvider != null) { locationProvider.reset(); locationProvider.setLocationListener(null, -1, -1, -1); }

Criteria myCriteria = new Criteria(); myCriteria.setPreferredResponseTime(Criteria.NO_REQUIREMENT); myCriteria.setCostAllowed(true);

Development Guide Retrieving the location of a BlackBerry device

37

Page 40: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

if ( gpsMode == GPSInfo.GPS_MODE_AUTONOMOUS ) { myCriteria.setCostAllowed(false); } else if ( gpsMode == GPSInfo.GPS_MODE_ASSIST ) { myCriteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_MEDIUM); } else { myCriteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_LOW); }

try { locationProvider = LocationProvider.getInstance(myCriteria);

if (locationProvider != null) { locationProvider.setLocationListener (new myLocationListener(), -1, -1, -1); } } catch (Exception err) { } }

private static class myLocationListener implements LocationListener { public void locationUpdated(LocationProvider provider, Location location) { lat = location.getQualifiedCoordinates().getLatitude(); lon = location.getQualifiedCoordinates().getLongitude(); alt = location.getQualifiedCoordinates().getAltitude(); spd = location.getSpeed(); crs = location.getCourse(); }

public void providerStateChanged(LocationProvider provider, int newState) { } }}

Development Guide

38

Page 41: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Error handlingYou can retrieve the last error that was received when a GPS fix is unsuccessful by invoking GPSInfo.getLastGPSError(), available in the JSR 179 Location API, or BlackBerryLocation.getError(), available in the BlackBerry® extensionsto JSR 179.

Handle errors (JSR 179)If a request for a GPS fix is unsuccessful, you can retrieve the last returned error.

1. Import the required class.

import net.rim.device.api.gps.GPSInfo;

2. Create a class and a constructor.

public class handleGPS{ public handleGPS() { }}

3. In the constructor, invoke GPSInfo.getLastGPSError() to retrieve the error.

switch (GPSInfo.getLastGPSError()){ case GPSInfo.GPS_ERROR_NONE: break; case GPSInfo.GPS_ERROR_ALMANAC_OUTDATED: break; case GPSInfo.GPS_ERROR_AUTHENTICATION_FAILURE: break; case GPSInfo.GPS_ERROR_CHIPSET_DEAD: break; case GPSInfo.GPS_ERROR_DEGRADED_FIX_IN_ALLOTTED_TIME: break; case GPSInfo.GPS_ERROR_GPS_LOCKED: break; case GPSInfo.GPS_ERROR_INVALID_NETWORK_CREDENTIAL: break; case GPSInfo.GPS_ERROR_INVALID_REQUEST: break; case GPSInfo.GPS_ERROR_LOW_BATTERY: break; case GPSInfo.GPS_ERROR_NETWORK_CONNECTION_FAILURE: break; case GPSInfo.GPS_ERROR_NO_FIX_IN_ALLOTTED_TIME: break; case GPSInfo.GPS_ERROR_NO_SATELLITE_IN_VIEW: break; case GPSInfo.GPS_ERROR_PRIVACY_ACCESS_DENIED: break; case GPSInfo.GPS_ERROR_SERVICE_UNAVAILABLE: break; case GPSInfo.GPS_ERROR_TIMEOUT_DEGRADED_FIX_NO_ASSIST_DATA: break; case GPSInfo.GPS_ERROR_TIMEOUT_NO_FIX_NO_ASSIST_DATA: break;}

Development Guide Error handling

39

Page 42: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Handle errors (BlackBerry extensions to JSR 179)You can check the status of a GPS fix request by invoking the getStatus() method that is provided in the BlackBerry®extensions to JSR 179. If the return is BlackBerryLocation.GPS_ERROR, you can retrieve the error value by invokingBlackBerryLocation.getError().

1. Import the required classes and interfaces.

import net.rim.device.api.gps.*;import javax.microedition.location.*;

2. Create a class and a constructor.

public class handleGPS{ public handleGPS() { }}

3. In the constructor, create a try/catch block. In this block, create an instance of the BlackBerryCriteria class bypassing the GPS mode to the constructor.

try{ BlackBerryCriteria myCriteria = new BlackBerryCriteria(GPSInfo.GPS_MODE_ASSIST);}catch ( UnsupportedOperationException ex ){ return;}

4. In the try/catch block, create another try/catch block. In this block, create an instance of theBlackBerryLocationProvider class by retrieving the BlackBerryCriteria object. InvokesetLocationListener() to specify the location listener.

try{ BlackBerryLocationProvider myProvider = (BlackBerryLocationProvider)LocationProvider.getInstance(myCriteria); myProvider.setLocationListener(new myLocationListener(), -1, -1, -1);}catch ( LocationException lex ){ return;}

5. In the class, create a static class that implements LocationListener. Implement locationUpdated() andproviderStateChanged().

Development Guide Error handling

40

Page 43: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

private static class myLocationListener implements LocationListener{ public void locationUpdated(LocationProvider provider, Location location) { }

public void providerStateChanged(LocationProvider provider, int newState) { }}

6. In locationUpdated(), verify if the location parameter is an instance of BlackBerryLocation. If so, thencreate a local BlackBerryLocation object by passing the location parameter. Invoke getStatus() to retrievethe status of GPS location request, and then process the returned status.

if (location instanceof BlackBerryLocation){ BlackBerryLocation bLoc = (BlackBerryLocation)location;

switch(bLoc.getStatus()) { case BlackBerryLocation.GPS_ERROR: int gpsStatus = bLoc.getError(); break;

case BlackBerryLocation.FAILOVER_MODE_ON: case BlackBerryLocation.SUBSEQUENT_MODE_ON: case BlackBerryLocation.GPS_FIX_PARTIAL: case BlackBerryLocation.GPS_FIX_COMPLETE: break; }}

Code sample: Handling errors (BlackBerry extensions to JSR 179)import net.rim.device.api.gps.*;import javax.microedition.location.*;

public class handleGPS{ public handleGPS() { try { BlackBerryCriteria myCriteria = new BlackBerryCriteria(GPSInfo.GPS_MODE_ASSIST);

try { BlackBerryLocationProvider myProvider = (BlackBerryLocationProvider)

Development Guide Error handling

41

Page 44: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

LocationProvider.getInstance(myCriteria); myProvider.setLocationListener (new myLocationListener(), -1, -1, -1); } catch ( LocationException lex ) { return; } } catch ( UnsupportedOperationException ex ) { return; } }

private static class myLocationListener implements LocationListener { public void locationUpdated (LocationProvider provider, Location location) { if (location instanceof BlackBerryLocation) { BlackBerryLocation bLoc = (BlackBerryLocation)location;

switch(bLoc.getStatus()) { case BlackBerryLocation.GPS_ERROR: int gpsStatus = bLoc.getError(); break;

case BlackBerryLocation.FAILOVER_MODE_ON: case BlackBerryLocation.SUBSEQUENT_MODE_ON: case BlackBerryLocation.GPS_FIX_PARTIAL: case BlackBerryLocation.GPS_FIX_COMPLETE: break; } } }

public void providerStateChanged (LocationProvider provider, int newState) { } }}

Retrieve a GPS location by using a web page

Development Guide Retrieve a GPS location by using a web page

42

Page 45: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

The following code sample demonstrates how to determine if a web page was loaded by the BlackBerry® Browser and if theBlackBerry device supports GPS functionality. If these conditions are true, the web page receives the updated location informationto start location tracking.

Code sample: Retrieving a GPS location by using a web page<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>GPS Testing</title> </head> <body> <script type="text/javascript">var modeCellsite = 0;var modeAssisted = 1;var modeAutonomous = 2;

function locationChanged(){ alert("Lat " + blackberry.location.latitude + " Lon " + blackberry.location.longitude + " Time " + blackberry.location.timestamp ); return true;}

if ( window.blackberry && blackberry.location.GPSSupported ){ var isUpdated = false; var theCount = 0;

alert("Location tracking is supported");

blackberry.location.onLocationUpdate("locationChanged()"); blackberry.location.setAidMode(modeAutonomous);

while ( theCount++ < 10 && !isUpdated ) isUpdated = blackberry.location.refreshLocation();}else{ document.write("Location tracking is not supported");} </script> </body></html>

Development Guide Retrieve a GPS location by using a web page

43

Page 46: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Retrieving a GPS location by using a web page

You can use JavaScript® to configure the GPS mode, and determine the current location of the BlackBerry® device by using theBlackBerry® Browser.

You can use the following JavaScript properties and methods to access the Location API from the BlackBerry Browser.

JavaScript property Description

blackberry .location .GPSSupported This property returns true when GPS is supported by the

BlackBerry device.

blackberry .location .latitude This property returns the current latitude, in degrees, of the

BlackBerry device. Positive values indicate northern latitude,

negative values indicate southern latitude.

blackberry .location .longitude This property returns the current longitude, in degrees, of the

BlackBerry device. Positive values indicate eastern longitude,

negative values indicate western longitude

blackberry .location .timestamp This property returns time (in milliseconds since epoch) at which

the blackberry .location object was updated.

JavaScript method Description

blackberry .location .setAidMode (mode) This method specifies which GPS mode the BlackBerry device will

use to determine the GPS location. The mode can be any one of

the following values:

• 0 for Cell Site mode

• 1 for Assisted mode

• 2 for Autonomous mode

blackberry .location .refreshLocation () This method requests an update of the location of the BlackBerry

device. This method is asynchronous, so the script continues

regardless of whether updated location information has been

received. To ensure that location information is updated before

reading it, you should first register a listener using

blackberry .location .onLocationUpdate() that

Development Guide Retrieve a GPS location by using a web page

44

Page 47: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

JavaScript method Description

reads blackberry .location .latitude and

blackberry .location .longitude, and then call

refreshLocation() afterwards.

blackberry .location .onLocationUpdate

("callback")

This method registers a listener that evaluates a string or calls a

function whenever the BlackBerry device receives updated location

information.

On BlackBerry devices running versions of BlackBerry® Device

Software earlier than version 4.6, this function must be passed as

a string that is evaluated each time the location is refreshed. On

BlackBerry devices running BlackBerry Device Software version 4.6

or later, you can pass a string, or use the method to register a

callback function.

Once onlocationUpdate() has been invoked, the callback

occurs whenever there is an update to the location information.

This can be as frequent as once every several seconds. If you have

passed the method a function, you can cancel the callback using

blackberry.location.removeLocationUpdate(). If

you have passed a string, the callback cannot be removed.

blackberry .location .removeLocationUpd

ate ()

This method removes a previously registered callback function. This

method is only supported on BlackBerry devices running

BlackBerry Device Software version 4.6 or later.

Development Guide Retrieve a GPS location by using a web page

45

Page 48: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Geolocation overview 3

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

When you retrieve location information from the geolocation service, the cell tower and WLAN access points information is storedlocally on the device. The next time you try to retrieve location information, the cache is checked first and if the location is thesame, 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 onthe 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 accesspoints is supported on BlackBerry devices that run BlackBerry Device Software 6.0 or later.

Geolocation modesWith BlackBerry® Java® SDK 6.0 and later, you can retrieve geolocation information by specifying one of the following modesthat are provided in the LocationInfo class ( net.rim.device.api.gps package):

Mode Description

GEOLOCATION_MODE This mode retrieves a location from among 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.

If you specify the GEOLOCATION_MODE or the GEOLOCATION_MODE_CELL mode and the BlackBerry device does not supportgeolocation, the location is obtained using the cell site mode that is provided by the wireless service provider. Cell site geolocationmight be provided by some wireless service providers on the CDMA network.

In BlackBerry® Java® Development Environment 5.0, the geolocation service provides location information by using cell towerpositioning. To retrieve a location by using geolocation, you must specify GPSInfo.GPS_MODE_CELLSITE as the mode.

Development Guide Geolocation overview

46

Page 49: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Retrieving the location of a device by using the geolocation serviceYou can use the geolocation service to retrieve the location of a BlackBerry® device by performing the following actions (whichare 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 modeBlackBerryCriteria myCriteria = new BlackBerryCriteria(LocationInfo.GEOLOCATION_MODE);

Code sample: Retrieving a location providerBlackBerryLocationProvider myProvider = (BlackBerryLocationProvider)LocationProvider.getInstance(myCriteria);

Code sample: Requesting a single geolocation fix or multiple geolocation fixes/* Single location fix */BlackBerryLocation myLocation = myProvider.getLocation(timeout); /* Multiple location fixes */myProvider.setLocationListener(…);

Code sample: Retrieving the location information for the devicedouble lat = myLocation.getQualifiedCoordinates().getLatitude();double lng = myLocation.getQualifiedCoordinates().getLongitude();double alt = myLocation.getQualifiedCoordinates().getAltitude();

Retrieve the location of a device by using the geolocation serviceThe following steps demonstrate how to create a UI application that provides the location of the BlackBerry® device by usingthe 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.*;

Development Guide Retrieving the location of a device by using the geolocation service

47

Page 50: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

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 newclass 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 isdescribed 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 theLabelField class to store the coordinates that display on the screen. Create two double variables to store the latitudeand 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 userclicks to retrieve the geolocation of the device. Invoke Field.setChangeListener() to listen for changes to thebutton. Invoke findGeolocation(), which is described in step 6, to retrieve the geolocation when the user clicks thebutton. Invoke add() to add the button to the screen. Create an instance of the LabelField class to display the resultingcoordinates and invoke add() to add the field to the screen.

Development Guide Retrieving the location of a device by using the geolocation service

48

Page 51: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

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 clearLabelField for the coordinates. Create an instance of the Thread class that invokes run(). This thread is used toprocess 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 passLocationInfo.GEOLOCATION_MODE as the mode to retrieve geolocation information. In the catch block, invokeshowException(), which is described in step 10, to display the error message for anUnsupportedOperationException.

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. InvokeLocationProvider.getInstance() with the BlackBerryCriteria object to retrieve a location provider. Inthe catch block, invoke showException(), which is described in step 10, to display the error message for aLocationException.

Development Guide Retrieving the location of a device by using the geolocation service

49

Page 52: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

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. InvokeBlackBerryLocationProvider.getLocation() with a parameter of -1 to retrieve a location provider by usingthe default timeout value. Invoke getLongitude() and getLatitude() to retrieve the longitudinal and latitudinalcoordinates respectively. Create an instance of the StringBuffer class and append the resulting coordinates to thebuffer. Create a String variable and invoke toString() with the StringBuffer object to return the String valuefor the coordinates. Invoke showResults()to display the results on the screen, which is described in step 9. In the firstcatch block, invoke showException(), which is described in step 10, to display the error message for anInterruptedException. In the second catch block, invoke showException(), which is described in step 10, todisplay 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 thedefinition of Runnable. Invoke setText() with the String variable to specify the resulting coordinates for theLabelField.

Development Guide Retrieving the location of a device by using the geolocation service

50

Page 53: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

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

Code sample: Retrieving the location of a device by using the geolocation serviceThe following code sample demonstrates how to create a UI application that provides the location of the BlackBerry® device byusing 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());

Development Guide Retrieving the location of a device by using the geolocation service

51

Page 54: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

}}

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 =

Development Guide Retrieving the location of a device by using the geolocation service

52

Page 55: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

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

Development Guide Retrieving the location of a device by using the geolocation service

53

Page 56: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

{ Dialog.alert(e.getMessage()); } }); }}

Retrieving the optimal fix with GPS and geolocationYou can retrieve the optimal location fix by requesting geolocation updates along with GPS updates. An optimal fix provides ageolocation fix when a GPS fix cannot be retrieved during the specified timeout period. You can use this request in an applicationthat requires the location of a BlackBerry® device at all times, and you are not concernced about how the location is retrieved.

The BlackBerryCriteria class, in the net.rim.device.api.gps package, provides the following methods forretrieving the optimal fix:

Method Description

enableGeolocationWithGPS() This method returns a GPS fix as soon as it is available or within the timeout period

that is specified in the location request. If the GPS fix is unavailable, a geolocation

fix is returned. You can use this method for single or multiple fix requests.

enableGeolocationWithGPS

(BlackBerryCriteria.FASTES

T_FIX_PREFERRED)

This method returns the first available fix, regardless of the location source (GPS or

geolocation). During the timeout period that is specified in the location request,

the first fix that is available from a location source is provided to the application.

You can use this mode only for single fix requests.

Retrieve the optimal single fixThe following steps demonstrate how to create a UI application that provides the fastest available location fix, which may comefrom a geolocation or GPS location source. The location coordinates and the mode that the application uses to retrieve thelocation are displayed on the screen.

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.*;

Development Guide Retrieving the optimal fix with GPS and geolocation

54

Page 57: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass 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 SingleFixScreen class, which is describedin step 3, represents the custom screen.

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

3. Create the framework for the custom screen by extending the MainScreen class. Create an instance of theLabelField class to store the coordinates that you want to display on the screen. Create two double variables to storethe values for latitude and longitude . Create an integer variable and a String variable to store the location mode.

class SingleFixScreen extends MainScreen { private LabelField _coordLabel; private double _latitude; private double _longitude; private int _modeUsed; private String _mode;}

4. In the screen constructor, invoke super() to create a default menu. Invoke setTitle() to specify the title for the screen.

public SingleFixScreen() { super(DEFAULT_CLOSE | DEFAULT_MENU); setTitle(new LabelField("Single Fix 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 userclicks to retrieve the location of the device. Invoke Field.setChangeListener() to listen for changes to the button.Invoke findLocation(), which is described in step 6, to retrieve the geolocation when the user clicks the button. Invokeadd() to add the button to the screen. Create an instance of the LabelField class to display the resulting coordinatesand invoke add() to add the field to the screen.

ButtonField locButton = new ButtonField("Get location fix", ButtonField.CONSUME_CLICK);locButton.setChangeListener(new FieldChangeListener(){

Development Guide Retrieving the optimal fix with GPS and geolocation

55

Page 58: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

public void fieldChanged(Field field, int context) { findLocation(); }});add(locButton); this._coordLabel = new LabelField();add(this._coordLabel);

6. Create the framework for the findLocation method. Invoke setText() with an empty String value to clearLabelField for the coordinates. Create an instance of the Thread class that invokes run(). This thread is used toprocess the retrieval of the location information. In run(), create a try/catch block to specify the criteria for retrievinga location. Create an instance of the BlackBerryCriteria class by invoking BlackBerryCriteria(). Noarguments are passed to BlackBerryCriteria(), so the default location mode is used. InvokeenableGeolocationWithGPS(BlackBerryCriteria.FASTEST_FIX_PREFERRED) to retrieve the firstavailable location fix. In the catch block, invoke showException(), which is described in step 10, to display the errormessage for an UnsupportedOperationException.

private void findLocation(){ this._coordLabel.setText(""); Thread locThread = new Thread() { public void run() { try { BlackBerryCriteria myCriteria = new BlackBerryCriteria(); myCriteria.enableGeolocationWithGPS(BlackBerryCriteria .FASTEST_FIX_PREFERRED); } catch (UnsupportedOperationException e) { showException(e); } } }; locThread.start();}

7. In the first try block, create a second try/catch block to retrieve a location provider. InvokeLocationProvider.getInstance() with the BlackBerryCriteria object to retrieve a location provider. Inthe catch block, invoke showException(), which is described in step 10, to display the error message for aLocationException.

try{ BlackBerryLocationProvider myProvider =

Development Guide Retrieving the optimal fix with GPS and geolocation

56

Page 59: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

(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. InvokeBlackBerryLocationProvider.getLocation() with a parameter of -1 to retrieve a location provider by usingthe default timeout value. Invoke getLongitude() and getLatitude() to retrieve the longitudinal and latitudinalcoordinates respectively. Invoke getGPSMode() to retrieve the mode that is used to retrieve the location. Create aswitch block to identify whether the mode used is GPS or geolocation. Create an instance of the StringBuffer classand append the resulting coordinates and mode to the buffer. Create a String variable and invoke toString() withthe StringBuffer object to return the String value for the coordinates. Invoke showResults() to display theresults on the screen, which is described in step 9. In the first catch block, invoke showException(), which is describedin step 10, to display the error message for an InterruptedException. In the second catch block, invokeshowException(), 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(); _modeUsed = myLocation.getGPSMode(); switch (_modeUsed) { case LocationInfo.GEOLOCATION_MODE: case LocationInfo.GEOLOCATION_MODE_CELL: case LocationInfo.GEOLOCATION_MODE_WLAN: _mode = "Geolocation"; break; default: _mode = "GPS"; } StringBuffer sb = new StringBuffer(); sb.append("Longitude: "); sb.append(_longitude); sb.append("\n"); sb.append("Latitude: "); sb.append(_latitude); sb.append("\n"); sb.append("Mode: "); sb.append(_mode); String msg = sb.toString(); showResults(msg);}catch (InterruptedException e){

Development Guide Retrieving the optimal fix with GPS and geolocation

57

Page 60: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

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 thedefinition of Runnable. Invoke setText() with the String variable to specify the resulting coordinates forLabelField.

private void showResults(final String msg){ Application.getApplication().invokeLater(new Runnable() { public void run() { SingleFixScreen.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 ofRunnable. 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()); } });}

Code sample: Retrieving the optimal single fixThe following code sample demonstrates how to create a UI application that provides the fastest available location fix, whichmay come from a geolocation or GPS location source.

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.*;

Development Guide Retrieving the optimal fix with GPS and geolocation

58

Page 61: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

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

class SingleFixScreen extends MainScreen { private LabelField _coordLabel; private double _latitude; private double _longitude; private int _modeUsed; private String _mode; public SingleFixScreen() { super(DEFAULT_CLOSE | DEFAULT_MENU);

setTitle(new LabelField("Single Fix Demo" , Field.USE_ALL_WIDTH | DrawStyle.HCENTER)); ButtonField locButton = new ButtonField("Get location fix", ButtonField.CONSUME_CLICK); locButton.setChangeListener(new FieldChangeListener() { public void fieldChanged(Field field, int context) { findLocation(); } }); add(locButton); this._coordLabel = new LabelField(); add(this._coordLabel); } private void findLocation() { this._coordLabel.setText(""); Thread locThread = new Thread() { public void run()

Development Guide Retrieving the optimal fix with GPS and geolocation

59

Page 62: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

{ try { BlackBerryCriteria myCriteria = new BlackBerryCriteria(); myCriteria.enableGeolocationWithGPS(BlackBerryCriteria .FASTEST_FIX_PREFERRED); try { BlackBerryLocationProvider myProvider = (BlackBerryLocationProvider)LocationProvider.getInstance(myCriteria); try { BlackBerryLocation myLocation =(BlackBerryLocation)myProvider.getLocation(-1); _longitude = myLocation.getQualifiedCoordinates().getLongitude(); _latitude = myLocation.getQualifiedCoordinates().getLatitude(); _modeUsed = myLocation.getGPSMode(); switch (_modeUsed) { case LocationInfo.GEOLOCATION_MODE: case LocationInfo.GEOLOCATION_MODE_CELL: case LocationInfo.GEOLOCATION_MODE_WLAN: _mode = "Geolocation"; break; default: _mode = "GPS"; } StringBuffer sb = new StringBuffer(); sb.append("Longitude: "); sb.append(_longitude); sb.append("\n"); sb.append("Latitude: "); sb.append(_latitude); sb.append("\n"); sb.append("Mode: "); sb.append(_mode); String msg = sb.toString(); showResults(msg); } catch (InterruptedException e) { showException(e); } catch (LocationException e) { showException(e); } }

Development Guide Retrieving the optimal fix with GPS and geolocation

60

Page 63: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

catch (LocationException e) { showException(e); } } catch (UnsupportedOperationException e) { showException(e); } } }; locThread.start(); }

private void showResults(final String msg) { Application.getApplication().invokeLater(new Runnable() { public void run() { SingleFixScreen.this._coordLabel.setText(msg); } }); } private void showException(final Exception e) { Application.getApplication().invokeLater(new Runnable() { public void run() { Dialog.alert(e.getMessage()); } }); }}

Retrieve optimal multiple fixesThe following steps demonstrate how to create a UI application that provides continuous location updates by retrieving GPSfixes when the fixes are available or within the specified timeout period. If the GPS fix is unavailable, a geolocation fix is returnedinstead.

Before you begin: Verify that the BlackBerry® device or BlackBerry Smartphone Simulator has GPS enabled.

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.*;

Development Guide Retrieving the optimal fix with GPS and geolocation

61

Page 64: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

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. Create an integer variable and assign it avalue of 1, which specifies the interval to update the location coordinates. Create a variable with the type EditField tostore the location updates that displays on the screen. In main(), create an instance of the new class and invokeenterEventDispatcher() to enable the application to receive events. In the application constructor, create aninstance of the MultipleFixScreen class, which is described in step 7. Invoke setTitle() to specify the title forthe screen. Create an instance of the EditField class and add the field to the screen. Invoke startLocationUpdate(), which is described in step 4, to start retrieving location updates. Invoke pushScreen() to display the custom screenfor the application.

public class MultipleFixDemo extends UiApplication { private static int _interval = 1; private EditField _status; public static void main(String[] args) { new MultipleFixDemo().enterEventDispatcher(); }

public MultipleFixDemo() { MultipleFixScreen screen = new MultipleFixScreen(); screen.setTitle("Multiple Fix Demo"); _status = new EditField(Field.NON_FOCUSABLE); screen.add(_status); startLocationUpdate(); pushScreen(screen); }}

3. Create an updateLocationScreen method that invokes invokeLater() to add this section of code to the eventqueue 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() to display the results on the screen.

private void updateLocationScreen(final String msg){ invokeLater(new Runnable() { public void run() { _status.setText(msg); } });}

Development Guide Retrieving the optimal fix with GPS and geolocation

62

Page 65: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

4. Create the framework for the startLocationUpdate method. Create a try/catch block for specifying the criteriato retrieve a location. Create an instance of the BlackBerryCriteria class by invoking BlackBerryCriteria(). The default location mode is used because no arguments are passed to BlackBerryCriteria(). InvokeenableGeolocationWithGPS() to specify retrieving a GPS fix if it's available, or retrieving a geolocation fix if theGPS fix is unavailable. In the catch block, catch an UnsupportedOperationException, which indicates the locationmode is unsupported.

private void startLocationUpdate(){ try { BlackBerryCriteria myCriteria = new BlackBerryCriteria(); myCriteria.enableGeolocationWithGPS(); catch (UnsupportedOperationException ue) { System.err.println("Require mode is unavailable"); System.err.println(ue); System.exit(0); } return;}

5. In the first try block, create a second try/catch block to retrieve a location provider. InvokeLocationProvider.getInstance() with the BlackBerryCriteria object to retrieve a location provider.Create an instance of Runnable and pass it as a parameter to invokeLater(). Override run() in the definition ofRunnable and display a message that indicates the location provider could not be retrieved. InvokesetLocationListener() by passing the interval value, timeout value, and maximum age as parameters to register alistener when a location provider is available. In the catch block, catch a LocationException, which indicates thelocation provider is unavailable.

try{ BlackBerryLocationProvider myProvider = (BlackBerryLocationProvider)LocationProvider.getInstance(myCriteria); if ( myProvider == null ) { Runnable showUnsupportedDialog = new Runnable() { public void run() { Dialog.alert("Location service unsupported, exiting..."); System.exit( 1 ); } }; invokeLater( showUnsupportedDialog ); } else {

Development Guide Retrieving the optimal fix with GPS and geolocation

63

Page 66: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

myProvider.setLocationListener(new LocationListenerImpl(), _interval, 1, 1); }}catch (LocationException le){ System.err.println("Failed to retrieve a location provider"); System.err.println(le); System.exit(0);}

6. Create a second class that implements LocationListener. Implement locationUpdated() to provide locationupdates. Create an if statement to check that the location is valid. If the location is valid, retrieve the coordinates for thelongitude, latitude, and altitude by invoking getLongitude(), getLatitude() and getAltitude() respectively.Create an instance of the StringBuffer class and append the resulting coordinates to the buffer. InvokeupdateLocationScreen() to display the resulting coordinates on the screen.

private class LocationListenerImpl implements LocationListener{ public void locationUpdated(LocationProvider provider, Location location) { if(location.isValid()) { double longitude = location.getQualifiedCoordinates().getLongitude(); double latitude = location.getQualifiedCoordinates().getLatitude(); float altitude = location.getQualifiedCoordinates().getAltitude(); StringBuffer sb = new StringBuffer(); sb.append("Longitude: "); sb.append(longitude); sb.append("\n"); sb.append("Latitude: "); sb.append(latitude); sb.append("\n"); sb.append("Altitude: "); sb.append(altitude); sb.append(" m"); MultipleFixDemo.this.updateLocationScreen(sb.toString()); } } public void providerStateChanged(LocationProvider provider, int newState) { // Not implemented } }

7. Create the framework for the custom screen by extending the MainScreen class. In the screen constructor, invoke super() to create a default menu. Create an instance of the RichTextField to display an instructional message. Invoke add() to add the RichTextField to the screen.

Development Guide Retrieving the optimal fix with GPS and geolocation

64

Page 67: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

private final static class MultipleFixScreen extends MainScreen{ MultipleFixScreen() { super(DEFAULT_CLOSE | DEFAULT_MENU); RichTextField instructions = new RichTextField("Waiting for location update...",Field.NON_FOCUSABLE); this.add(instructions); }}

Code sample: Retrieving optimal multiple fixesThe following code sample demonstrates how to create a UI application that provides continuous location updates by retrievingGPS fixes when the fixes are available or within the specified timeout period. If the GPS fix is unavailable, a geolocation fix isreturned instead.

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.*;

public class MultipleFixDemo extends UiApplication { private static int _interval = 1; private EditField _status; public static void main(String[] args) { new MultipleFixDemo().enterEventDispatcher(); }

public MultipleFixDemo() { MultipleFixScreen screen = new MultipleFixScreen(); screen.setTitle("Multiple Fix Demo"); _status = new EditField(Field.NON_FOCUSABLE); screen.add(_status); startLocationUpdate(); pushScreen(screen); } private void updateLocationScreen(final String msg) { invokeLater(new Runnable()

Development Guide Retrieving the optimal fix with GPS and geolocation

65

Page 68: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

{ public void run() { _status.setText(msg); } }); }

private void startLocationUpdate() { try { BlackBerryCriteria myCriteria = new BlackBerryCriteria(); myCriteria.enableGeolocationWithGPS(); try { BlackBerryLocationProvider myProvider = (BlackBerryLocationProvider)LocationProvider.getInstance(myCriteria); if ( myProvider == null ) { Runnable showUnsupportedDialog = new Runnable() { public void run() { Dialog.alert("Location service unsupported, exiting..."); System.exit( 1 ); } }; invokeLater( showUnsupportedDialog ); } else { myProvider.setLocationListener(new LocationListenerImpl(), _interval, 1, 1); } } catch (LocationException le) { System.err.println("Failed to retrieve a location provider"); System.err.println(le); System.exit(0); } } catch (UnsupportedOperationException ue) { System.err.println("Require mode is unavailable"); System.err.println(ue); System.exit(0); } return;

Development Guide Retrieving the optimal fix with GPS and geolocation

66

Page 69: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

} private class LocationListenerImpl implements LocationListener { public void locationUpdated(LocationProvider provider, Location location) { if(location.isValid()) { double longitude = location.getQualifiedCoordinates().getLongitude(); double latitude = location.getQualifiedCoordinates().getLatitude(); float altitude = location.getQualifiedCoordinates().getAltitude(); StringBuffer sb = new StringBuffer(); sb.append("Longitude: "); sb.append(longitude); sb.append("\n"); sb.append("Latitude: "); sb.append(latitude); sb.append("\n"); sb.append("Altitude: "); sb.append(altitude); sb.append(" m"); MultipleFixDemo.this.updateLocationScreen(sb.toString()); } } public void providerStateChanged(LocationProvider provider, int newState) { // Not implemented } } private final static class MultipleFixScreen extends MainScreen { MultipleFixScreen() { super(DEFAULT_CLOSE | DEFAULT_MENU); RichTextField instructions = new RichTextField("Waiting for location update...",Field.NON_FOCUSABLE); this.add(instructions); } } }

Development Guide

67

Page 70: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Requesting concurrent GPS and geolocation updatesYou can request both GPS and geolocation updates concurrently. Requesting concurrent updates provides you with flexibility inyour application to specify request parameters (for example, the frequency and timeout), and to select the most suitable locationinformation to use based on customized criteria. For example, you might want to provide BlackBerry® device users with a quick,approximate location (by using geolocation) before a more accurate GPS fix is available.

To request both GPS and geolocation updates, you must create two separate threads to request separate instances of aBlackBerryLocationProvider. One thread specifies a GPS location mode, and the other thread specifies a geolocationmode.

Code sample: Requesting concurrent GPS and geolocation updates//In a GPS threadtry{ BlackBerryLocationProvider provider = (BlackBerryLocationProvider)LocationProvider.getInstance(new BlackBerryCriteria(GPSInfo.GPS_MODE_ASSIST));} catch (LocationException e){ showException(e);}

//In a geolocation threadtry{ BlackBerryLocationProvider provider = (BlackBerryLocationProvider)LocationProvider.getInstance(new BlackBerryCriteria(LocationInfo.GEOLOCATION_MODE_CELL));}catch (LocationException e){ showException(e);}

Development Guide Requesting concurrent GPS and geolocation updates

68

Page 71: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Geocoding and reverse geocoding 4

The net.rim.device.api.lbs.Locator API provides the geocoding methods that can allow you to request geospatialcoordinates for a street address. It also provides the reverse geocoding methods that can allow you to request a street addressfor a geospatial coordinate.

You can use the geocode() methods to request geospatial coordinates. A successful request returns an array of Landmarkobjects.

You can use the reverseGeocode() methods to request an approximate street address, city, province/state, or country. Asuccessful request returns an array of Landmark objects. A Landmark object can contain a display label name, a description,the geospatial coordinates, and a street address.

Requests for geocoding and reverse geocoding information are synchronous and can be interrupted. A BlackBerry® deviceapplication can use the Locator class to make only one request at a time.

Your application must invoke the geocode() and reverseGeocode() methods outside of the event dispatch thread.Requests to these methods that are made on the event dispatch thread are denied and result in anIllegalThreadStateException. Each request is sent to theBlackBerry® Infrastructure. If a request is unsuccessful, aLocatorException is thrown with an error code that indicates why the request is unsuccessful. If a request is unsuccessfulor stalls at the transport level, it is cancelled as specified by the value for REQUEST_TIMEOUT.

If the LBS Map API module (net_rim_bb_lbs_api) is not installed on a BlackBerry device, then invoking the geocode()and reverseGeocode() methods throws a MapServiceException.

The BlackBerry device does not cache requests.

Retrieve geospatial coordinates for an address by using geocodingYou can retrieve geospatial coordinates by invoking Locator.geocode(). When you invoke Locator.geocode(), youmust specify a street address by using an AddressInfo object or a String object of address information. Your applicationmust request geocoding information outside of the event dispatch thread. A successful request for geocoding information willreturn an array of Landmark objects.

1. Import the required classes.

import net.rim.device.api.lbs.*;import javax.microedition.location.*;

2. Create a class and a constructor.

public class myGeocode{ public myGeocode()

Development Guide Geocoding and reverse geocoding

69

Page 72: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

{ }}

3. In the class, create a private variable of type Thread.

private Thread geocoder;

4. In the constructor, create an instance of the Thread class. You cannot retrieve geocoding information on the application'sprimary thread.

geocoder = new Thread(thread);geocoder.setPriority(Thread.MIN_PRIORITY);geocoder.start();

5. In the class, create a Thread that invokes a public run() method. In run(), create an instance of the AddressInfoclass. Populate the object with address information. Create an instance of the Coordinates class by passing the latitude,longitude, and altitude values to the constructor to start the geocode search. In the following code sample, the positivenorthern latitude and negative western longitude of the Waterloo, Ontario region are used by the LBS Locate Server toperform the geocode search. Create a try/catch block. In this block, invoke geocode() to find the address and returnthe results in a Landmark array.

Runnable thread = new Runnable(){ public void run() { AddressInfo addrInfo = new AddressInfo();

addrInfo.setField(AddressInfo.STREET, "455 Phillip Street"); addrInfo.setField(AddressInfo.CITY, "Waterloo"); addrInfo.setField(AddressInfo.STATE, "Ontario"); addrInfo.setField(AddressInfo.POSTAL_CODE, "N2L 3X2"); addrInfo.setField(AddressInfo.COUNTRY, "Canada");

Coordinates coord = new Coordinates(43.28, -80.31, Float.NaN);

try { Landmark[] results = Locator.geocode(addrInfo, coord); } catch ( LocatorException lex ) { } }};

Code sample: Retrieving geospatial coordinates for an address by using geocodingimport net.rim.device.api.lbs.*;import javax.microedition.location.*;

Development Guide Retrieve geospatial coordinates for an address by using geocoding

70

Page 73: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

public class myGeocode{ private Thread geocoder;

public myGeocode() { geocoder = new Thread(thread); geocoder.setPriority(Thread.MIN_PRIORITY); geocoder.start(); }

Runnable thread = new Runnable() { public void run() { AddressInfo addrInfo = new AddressInfo();

addrInfo.setField(AddressInfo.STREET, "455 Phillip Street"); addrInfo.setField(AddressInfo.CITY, "Waterloo"); addrInfo.setField(AddressInfo.STATE, "Ontario"); addrInfo.setField(AddressInfo.POSTAL_CODE, "N2L 3X2"); addrInfo.setField(AddressInfo.COUNTRY, "Canada");

Coordinates coord = new Coordinates(43.28, -80.31, Float.NaN);

try { Landmark[] results = Locator.geocode(addrInfo, coord); } catch ( LocatorException lex ) { } } };}

Retrieve an address by using reverse geocodingYou can use geospatial coordinates to retrieve an address by invoking Locator.reverseGeocode(). You must specify thecoordinates for the latitude and longitude by using two int fields, or by using a Coordinates object. The values for thecoordinates are passed as decimal degrees, to five decimal places, with the values multiplied by 100,000. Your application mustrequest reverse geocoding information, such as an address, outside of the event dispatch thread. A successful request for reversegeocoding information returns an array of Landmark objects.

1. Import the required classes.

import net.rim.device.api.lbs.*;import javax.microedition.location.*;

2. Create a class and a constructor.

Development Guide Retrieve an address by using reverse geocoding

71

Page 74: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

public class myReverseGeocode{ public myReverseGeocode() { }}

3. In the class, create a private variable of type Thread.

private Thread reverseGeocode;

4. In the constructor, create an instance of the Thread class. You cannot retrieve reverse geocoding information on theapplication's primary thread.

reverseGeocode = new Thread(thread);reverseGeocode.setPriority(Thread.MIN_PRIORITY);reverseGeocode.start();

5. In the class, create an instance of Thread that invokes a public run() method. In run(), create an instance of theAddressInfo class. Create two int fields, and populate the fields with the values for thelatitude and longitude with fivedecimal accuracy multiplied by 100,000. Create a try/catch block. In this block, invoke reverseGeocode() to findthe address and return the results in a Landmark array.

Runnable thread = new Runnable(){ public void run() { AddressInfo addrInfo = null;

int latitude = (int)(45.423488 * 100000); int longitude = (int)(-80.32480 * 100000);

try { Landmark[] results = Locator.reverseGeocode (latitude, longitude, Locator.ADDRESS );

if ( results != null && results.length > 0 ) addrInfo = results[0].getAddressInfo(); } catch ( LocatorException lex ) { } }};

6. Specify the search type by passing one of the following parameters to Locator.reverseGeocode():• Locator.ADDRESS: returns the nearest address or nearest street to the specified latitude/longitude• Locator.CITY: returns a value that is focused on the city level• Locator.COUNTRY: returns a value that is focused on the country level

Development Guide Retrieve an address by using reverse geocoding

72

Page 75: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

• Locator.PROVINCE_STATE: returns a value that is focused on the province or state level• Locator.POSTAL_CODE: returns a value that is focused on the postal code or zip code level

Code sample: Retrieving an address by using geospatial coordinates andreverse geocodingimport net.rim.device.api.lbs.*;import javax.microedition.location.*;

public class myReverseGeocode{ private Thread reverseGeocode;

public myReverseGeocode() { reverseGeocode = new Thread(thread); reverseGeocode.setPriority(Thread.MIN_PRIORITY); reverseGeocode.start(); }

Runnable thread = new Runnable() { public void run() { AddressInfo addrInfo = null;

int latitude = (int)(45.423488 * 100000); int longitude = (int)(-80.32480 * 100000);

try { Landmark[] results = Locator.reverseGeocode (latitude, longitude, Locator.ADDRESS );

if ( results != null && results.length > 0 ) addrInfo = results[0].getAddressInfo(); } catch ( LocatorException lex ) { } } };}

Development Guide Code sample: Retrieving an address by using geospatial coordinates and reverse geocoding

73

Page 76: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

BlackBerry Maps 5

You can create a BlackBerry® device application that interacts with BlackBerry® Maps. BlackBerry Maps is a map and locationapplication that can display a map, the location of the BlackBerry device, a route from a starting location to a specific endinglocation, and points of interest on a map.

Your application can interact with BlackBerry Maps in the following ways:

• Open BlackBerry Maps from your BlackBerry device application.• Display KML overlays on BlackBerry Maps.• Open BlackBerry Maps from the BlackBerry Browser.• Embed a map in your BlackBerry device application.

BlackBerry Maps can be installed on BlackBerry devices that are running BlackBerry® Device Software 4.2 or later.

You can use the MapsArguments class in the net.rim.blackberry.api.invoke package to create a BlackBerry deviceapplication that interacts with BlackBerry Maps.

Opening BlackBerry Maps from your applicationYou can open BlackBerry® Maps by using the Invoke.invokeApplication() method. When you use this method, youmust pass in a net.rim.blackberry.api.invoke.MapsArguments parameter to customize the map view thatappears.

You can use the following methods to specify how you want to open BlackBerry Maps:

• Use the default settings by invoking MapsArgument().• Use address information for a contact by invoking MapsArguments(Contact, int).• Display the location of a landmark by invoking MapsArguments(Landmark[]).• Display a location at specific coordinates by invoking MapsArguments(MapView).• Use a location document by invoking MapsArguments(String, String).• Use local search information by invoking MapsArguments(ARG_LOCAL_SEARCH, String, String).

Open BlackBerry Maps by using the default settingsYou can open BlackBerry® Maps to display the default map view by invoking Invoke.invokeApplication() and passingin a new MapsArguments object.

1. Import the required classes.

import net.rim.blackberry.api.invoke.*;

2. Create a class and a constructor to use to invoke BlackBerry Maps.

Development Guide BlackBerry Maps

74

Page 77: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

public class invokeMaps{ public invokeMaps() { }}

3. In the constructor, invoke Invoke.invokeApplication() to open BlackBerry Maps. Pass in a newMapsArguments object.

Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, new MapsArguments());

Code sample: Opening BlackBerry Maps by using the default settingsimport net.rim.blackberry.api.invoke.*;

public class invokeMaps{ public invokeMaps() { Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, new MapsArguments()); }}

Open BlackBerry Maps by using information from a contactYou can open BlackBerry® Maps to display a location on a map by using the address information from a contact in the contactsapplication on the BlackBerry device.

1. Import the required classes and interfaces.

import net.rim.blackberry.api.invoke.*;import javax.microedition.pim.*;

2. Create a class and constructor to use to invoke BlackBerry Maps.

public class invokeMaps{ public invokeMaps () { }}

3. In the constructor, retrieve an instance of a ContactList object from the BlackBerry device. Create a contact by usingthe Contact class. Populate the Contact with the name and address of the contact.

ContactList contacts = null;try{ contacts = (ContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY);

Development Guide Open BlackBerry Maps by using information from a contact

75

Page 78: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

}catch (PIMException e){ return;}

Contact contact = contacts.createContact();contact.addString(Contact.FORMATTED_NAME, PIMItem.ATTR_NONE, "Ms. Andrea Aime");contact.addString(Contact.FORMATTED_ADDR, PIMItem.ATTR_NONE, "455 Phillip St. Waterloo ON N2L3X2 Canada");

String[] name = new String[ contacts.stringArraySize( Contact.NAME ) ];name[ Contact.NAME_GIVEN ] = "Andrea";name[ Contact.NAME_FAMILY ] = "Aime";name[ Contact.NAME_PREFIX ] = "Ms.";

String[] addr = new String[ contacts.stringArraySize( Contact.ADDR ) ];addr[ Contact.ADDR_STREET ] = "455 Phillip St";addr[ Contact.ADDR_LOCALITY ] = "Waterloo";addr[ Contact.ADDR_REGION ] = "ON";addr[ Contact.ADDR_POSTALCODE ] = "N2L3X2";addr[ Contact.ADDR_COUNTRY ] = "Canada";

4. In the constructor, create a MapsArguments object by passing in the Contact object with an offset of zero. InvokeInvoke.invokeApplication() to open BlackBerry Maps. Pass in the MapsArguments object.

MapsArguments mapsArgs = new MapsArguments(contact, 0);Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, mapsArgs);

Code sample: Invoking BlackBerry Maps by using information from a contactimport net.rim.blackberry.api.invoke.*;import javax.microedition.pim.*;

public class invokeMaps{ public invokeMaps() { ContactList contacts = null;

try { contacts = (ContactList) PIM.getInstance().openPIMList (PIM.CONTACT_LIST, PIM.READ_ONLY); } catch (PIMException e) { return; }

Contact contact = contacts.createContact();

Development Guide Open BlackBerry Maps by using information from a contact

76

Page 79: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

contact.addString(Contact.FORMATTED_NAME, PIMItem.ATTR_NONE, "Ms. Andrea Aime"); contact.addString(Contact.FORMATTED_ADDR, PIMItem.ATTR_NONE, "455 Phillip St. Waterloo ON N2L3X2 Canada");

String[] name = new String[ contacts.stringArraySize( Contact.NAME ) ]; name[ Contact.NAME_GIVEN ] = "Andrea"; name[ Contact.NAME_FAMILY ] = "Aime"; name[ Contact.NAME_PREFIX ] = "Ms.";

String[] addr = new String[ contacts.stringArraySize( Contact.ADDR ) ]; addr[ Contact.ADDR_STREET ] = "455 Phillip St"; addr[ Contact.ADDR_LOCALITY ] = "Waterloo"; addr[ Contact.ADDR_REGION ] = "ON"; addr[ Contact.ADDR_POSTALCODE ] = "N2L3X2"; addr[ Contact.ADDR_COUNTRY ] = "Canada";

MapsArguments mapsArgs = new MapsArguments(contact, 0); Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, mapsArgs); }}

Open BlackBerry Maps by using specific coordinatesYou can open BlackBerry® Maps to display a location on a map by providing the coordinates for the latitude and longitude of alocation and by specifying the zoom and rotation values. The zoom values have a range of 0 to MapView.MAX_ZOOM. Therotation values are expressed in degrees to rotate the map from north facing up, and have a range of 0 to 359.

1. Import the required classes.

import net.rim.blackberry.api.invoke.*;import net.rim.blackberry.api.maps.*;

2. Create a class and constructor to use to invoke BlackBerry Maps.

public class invokeMaps{ public invokeMaps () { }}

3. In the constructor, create an instance of the MapView class. Invoke MapView.setLatitude(),MapView.setLongitude(), and MapView.setZoom() to specify the coordinates and zoom that you want to use.

MapView mapView = new MapView();mapView.setLatitude(4328915);mapView.setLongitude(-8032480);mapView.setZoom(10);

Development Guide Open BlackBerry Maps by using specific coordinates

77

Page 80: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

4. In the constructor, create an instance of the MapsArguments class using the MapView object as an argument. InvokeInvoke.invokeApplication() to open BlackBerry Maps and pass in the MapsArguments object.

MapsArguments mapsArgs = new MapsArguments(mapView);Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, mapsArgs);

Code sample: Invoking BlackBerry Maps by using specific coordinatesimport net.rim.blackberry.api.invoke.*;import net.rim.blackberry.api.maps.*;

public class invokeMaps{ public invokeMaps() { MapView mapView = new MapView(); mapView.setLatitude(4328915); mapView.setLongitude(-8032480); mapView.setZoom(10); MapsArguments mapsArgs = new MapsArguments(mapView); Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, mapsArgs); }}

Open BlackBerry Maps by using a landmarkYou can open BlackBerry® Maps to display the location of a landmark on a map by specifying an array of Landmark objects. Alandmark object can contain a display label name, a description, the geospatial coordinates, and a street address.

If you do not specify the coordinates, BlackBerry Maps can use the address to find the coordinates. If the coordinates and addressare invalid, BlackBerry Maps does not display the location of the landmark.

1. Import the required classes.

import net.rim.blackberry.api.invoke.*;import javax.microedition.location.*;

2. Create a class and constructor to use to invoke BlackBerry Maps.

public class invokeMaps{ public invokeMaps () { }}

3. In the constructor, create an array of Landmark objects that you can use to add the landmark information to.

Landmark[] landMarks = new Landmark[3];

Development Guide Open BlackBerry Maps by using a landmark

78

Page 81: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

4. In the constructor, create an AddressInfo array and invoke AddressInfo.setField() to specify the street address.Add the AddressInfo array to the Landmark array.

AddressInfo addressInfo = new AddressInfo();addressInfo.setField(AddressInfo.STREET, "455 Phillip St");addressInfo.setField(AddressInfo.CITY, "Waterloo");addressInfo.setField(AddressInfo.STATE, "Ontario");landMarks[0] = new Landmark("AAA", "Description 1", null, addressInfo);

5. In the constructor, create an instance of the QualifiedCoordinates class and specify the coordinates. Add theQualifiedCoordinates to the Landmark array.

QualifiedCoordinates coordinates = new QualifiedCoordinates(45.4, -75.1, 0, 0, 0);landMarks[1] = new Landmark("BBB", "Description 2", coordinates, null);coordinates = new QualifiedCoordinates(45.3,-75.3,0,0,0);landMarks[2] = new Landmark("CCC", "Description 3", coordinates, null);

6. In the constructor, create an instance of the MapsArguments class using the Landmarks array as an argument. InvokeInvoke.invokeApplication() to open BlackBerry Maps. Pass in the MapsArguments object.

MapsArguments ma = new MapsArguments(landMarks); Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, ma);

Code sample: Opening BlackBerry Maps by using a landmarkimport net.rim.blackberry.api.invoke.*;import javax.microedition.location.*;

public class invokeMaps{ public invokeMaps () { Landmark[] landMarks = new Landmark[3];

AddressInfo addressInfo = new AddressInfo(); addressInfo.setField(AddressInfo.STREET, "455 Phillip St"); addressInfo.setField(AddressInfo.CITY, "Waterloo"); addressInfo.setField(AddressInfo.STATE, "Ontario");

landMarks[0] = new Landmark("AAA", "Description 1", null, addressInfo);

QualifiedCoordinates coordinates = new QualifiedCoordinates(45.4, -75.1, 0, 0, 0);

landMarks[1] = new Landmark("BBB", "Description 2", coordinates, null);

coordinates = new QualifiedCoordinates(45.3,-75.3,0,0,0);

landMarks[2] = new Landmark("CCC", "Description 3", coordinates, null);

MapsArguments ma = new MapsArguments(landMarks);

Development Guide Open BlackBerry Maps by using a landmark

79

Page 82: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, ma); }}

Opening BlackBerry Maps by using a location documentYou can open BlackBerry® Maps to display map locations and routes by passing in a location document. A location document isa String object that contains XML elements with attributes that can specify the location and route information. The XMLelements that you can use include <lbs>, <getRoute> and <location>.

XML element: <lbs>The opening and closing <lbs> elements wrap the location document elements.

Valid parentsNone

Valid children<location>, <getRoute>

Attributes

Attribute Type Description Supported in

id String This value specifies the ID of a location

document.

BlackBerry® Java®

Development Environment

4.5.0 or later

clear String This value specifies the clearing action to

perform on the information in a map. The

value is a list of location document IDs

separated by commas, or one of the

following values:

• NONE: does not clear any information

• DOCS: clears location and route

information from all location

documents that have a specific id

attribute

BlackBerry JDE 4.5.0 or later

Development Guide Opening BlackBerry Maps by using a location document

80

Page 83: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Attribute Type Description Supported in

• LOCATIONS: clears all the location

information from the map

• ROUTES: clears all route the

information from the map

• ALL: clears all the location and route

information from the map

Code sample<lbs clear='WatLocation'></lbs><lbs clear='WatLocation,OttLocation'></lbs><lbs clear='WatRoute'></lbs><lbs clear='WatRoute,OttRoute'></lbs><lbs clear='NONE'></lbs><lbs clear='DOCS'></lbs><lbs clear='LOCATIONS'></lbs><lbs clear='ROUTES'></lbs><lbs clear='ALL'></lbs>

<lbs clear='ALL' id='Wat'> <location x='-8052237' y='4346518' label='Waterloo, ON' description='Waterloo' zoom='10' /></lbs>

XML element: <location>The <location> element contains information for a specific location. The description, label, x and y are requiredattributes.

Valid parents<lbs>, <getRoute>

Valid childrenNone

Attributes

Attribute Type Description Supported in

address String This attribute specifies the street address. BlackBerry® Java® Development

Environment 4.2.1 or later

categories String This attribute specifies the category. BlackBerry JDE 4.2.1 or later

Development Guide Opening BlackBerry Maps by using a location document

81

Page 84: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Attribute Type Description Supported in

city String This attribute specifies the city. BlackBerry JDE 4.2.1 or later

country String This attribute specifies the country. BlackBerry JDE 4.2.1 or later

description String This attribute specifies the description

information for a location.

This is a required attribute.

BlackBerry JDE 4.2.0 or later

email String This attribute specifies the email address. BlackBerry JDE 4.2.1 or later

fax String This attribute specifies the fax number. BlackBerry JDE 4.2.1 or later

label String This attribute specifies the label that is

displayed beside a location on a map.

This is a required attribute.

BlackBerry JDE 4.2.0 or later

phone String This attribute specifies the phone number. BlackBerry JDE 4.2.1 or later

postalCode String This attribute specifies the postal code or zip

code.

BlackBerry JDE 4.2.1 or later

rating double This attribute specifies the rating

information in the range of 0 to 5.

BlackBerry JDE 4.2.1 or later

region String This attribute specifies the province or state. BlackBerry JDE 4.2.1 or later

url String This attribute specifies the URL. BlackBerry JDE 4.2.1 or later

x or the alias, lon integer This attribute specifies the longitude in

decimal degrees with five decimal accuracy

multiplied by 100,000.

This is a required attribute.

BlackBerry JDE 4.2.0 or later

y or the alias, lat integer This attribute specifies the latitude in

decimal degrees with five decimal accuracy

multiplied by 100,000.

This is a required attribute.

BlackBerry JDE 4.2.0 or later

zoom integer This attribute specifies the zoom level from

0 to 15.

BlackBerry JDE 4.2.0 or later

Code sample

Development Guide Opening BlackBerry Maps by using a location document

82

Page 85: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

<lbs id='Waterloo'> <location x='-8052237' y='4346518' label='Waterloo, ON' description='Waterloo' zoom='10' /></lbs>

XML element: <getRoute>The <getRoute> element contains the route information. To display route information in a map, you must place the startingand ending locations in two <location> elements in the <getRoute> block. You can use the x and y attributes, or the aliaseslon and lat, in a <location> element that you nest within the <getRoute> block.

Valid parents<lbs>

Valid children<location>

AttributesNone

Code sample<lbs> <getRoute> <location x='-8052237' y='4346518' label='Waterloo, ON' description='Waterloo, Ontario, Canada' /> <location lon='-7569792' lat='4542349' label='Ottawa, ON' description='Ottawa, Ontario, Canada' /> </getRoute></lbs>

Display and clear locations on a map by using a location documentYou can use a location document to display a location on a map in BlackBerry® Maps. You can also clear locations from a mapafter they are displayed.

1. Import the required classes.

import net.rim.blackberry.api.invoke.*;

2. Create a class and a constructor to use to invoke BlackBerry Maps.

public class invokeMaps{ public invokeMaps ()

Development Guide Opening BlackBerry Maps by using a location document

83

Page 86: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

{ }}

3. In the constructor, create a String variable to use for the location document. Add an <lbs> element. Configure a<location> element with the location that you want to display.

String document = "<lbs id='Waterloo'> <location x='-8052237' y='4346518' label='Waterloo, ON' description='Waterloo' zoom='10' /> </lbs>";

4. In the constructor, invoke Invoke.invokeApplication() using the APP_TYPE_MAPS constant and a newMapsArguments object as parameters to open BlackBerry Maps. Pass in the ARG_LOCATION_DOCUMENT property andthe String variable that represents the location document as parameters for the MapsArguments class to display thelocation provided in the location document.

Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, new MapsArguments (MapsArguments.ARG_LOCATION_DOCUMENT, document));

5. Perform one of the following tasks to clear location information from a map after it has been displayed :

Task Steps

Clear a location from a map. Create a String that configures the clear attribute to bethe id of the location document that contains the locationinformation.

String document = "<lbs clear='Waterloo'></lbs>";

Clear all locations from a map. Create a String that configures the clear attribute to beLOCATIONS.

String document = "<lbs clear='LOCATIONS'></lbs>";

Clear all locations and routes from a map. Create a String that configures the clear attribute to beALL.

String document = "<lbs clear='ALL'></lbs>";

Clearing map content occurs before any new map content is displayed on the map. You can combine the actions of displayingand clearing map content into one location document.

Development Guide Opening BlackBerry Maps by using a location document

84

Page 87: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

String document = "<lbs clear='Waterloo' id='NewZone'> <location x='-8050000' y='4340000' label='NewZone' description='NewZone' zoom='10' /> </lbs>";

Code sample: Displaying locations on a map by using a location documentimport net.rim.blackberry.api.invoke.*;

public class invokeMaps{ public invokeMaps () { String document = "<lbs id='Waterloo'> <location x='-8052237' y='4346518' label='Waterloo, ON' description='Waterloo' zoom='10' /> </lbs>"; Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, new MapsArguments (MapsArguments.ARG_LOCATION_DOCUMENT, document)); }}

Display and clear a route on a map by using a location documentYou can use a location document to display a route on a map in BlackBerry® Maps. You can also clear a route from a map afterit is displayed.

1. Import the required classes.

import net.rim.blackberry.api.invoke.*;

2. Create a class and constructor to use to invoke BlackBerry Maps.

public class invokeMaps{ public invokeMaps () { }}

3. In the constructor, create a String variable to use for the location document. Add an <lbs> and a <getRoute> element.Add <location> elements to specify the starting location and ending location of the route that you want to display.

String document = "<lbs id='WatRoute'><getRoute> <location x='-8052237' y='4346518' label='Waterloo, ON' description='Waterloo, Ontario, Canada' /> <location x='-7569792' y='4542349' label='Ottawa, ON' description='Ottawa, Ontario, Canada' /> </getRoute></lbs>";

Development Guide Opening BlackBerry Maps by using a location document

85

Page 88: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

4. In the constructor, invoke Invoke.invokeApplication() using the APP_TYPE_MAPS constant and a newMapsArguments object as parameters to open BlackBerry Maps. Pass in the ARG_LOCATION_DOCUMENT property andthe String variable that represents the location document as parameters for the MapsArguments class to display theroute provided in the location document.

invoke.invokeApplication(Invoke.APP_TYPE_MAPS, new MapsArguments (MapsArguments.ARG_LOCATION_DOCUMENT, document));

5. Perform one of the following tasks to clear route location information from a map after it has been displayed:

Task Steps

Clear a route from a map. Create a String that configures the clear attribute to bethe id of the location document that contains the routeinformation.

String document = "<lbs clear='WatRoute'></lbs>";

Clear all routes from a map. Create a String that configures the clear attribute to beROUTES.

String document = "<lbs clear='ROUTES'></lbs>";

Clear all routes and location information from a specificlocation documents with an id attribute.

Create a String that configures the clear attribute to beDOCS.

String document = "<lbs clear='DOCS'></lbs>";

Clear all routes and location information from a map. Create a String that configures the clear attribute to beALL.

String document = "<lbs clear='ALL'></lbs>";

Clearing map content occurs before any new map content is displayed on the map. You can combine the actions of displayingand clearing map content into one location document.

String document = "<lbs clear='WatRoute' id='NewRoute'><getRoute> <location x='-8051111' y='4341111' label='NewRoute #1' description='New Route #1' /> <location x='-7562222' y='4542222' label='NewRoute #2' description='New Route #2' /> </getRoute></lbs>";

Code sample: Displaying a route using a location document

Development Guide Opening BlackBerry Maps by using a location document

86

Page 89: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

import net.rim.blackberry.api.invoke.*;

public class invokeMaps{ public invokeMaps () { String document = "<lbs id='WatRoute'><getRoute> <location x='-8052237' y='4346518' label='Waterloo, ON' description='Waterloo, Ontario, Canada' /> <location x='-7569792' y='4542349' label='Ottawa, ON' description='Ottawa, Ontario, Canada' /> </getRoute></lbs>"; Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, new MapsArguments (MapsArguments.ARG_LOCATION_DOCUMENT, document)); }}

Open BlackBerry Maps by using a local searchYou can open BlackBerry® Maps to display points of interest that are nearby the location that you specify in your search criteria.The search criteria is a String that must include a business category or a business name, and a location. For example, you candisplay all the hotels in the city of Waterloo.

A business category is a type of business, such as coffee, gas, hotels, pizza, and restaurants.

The location is a String that is the name of a village, town, or city, or the latitudinal and longitudinal coordinates, separatedby a comma (for example, 4328915,-8032480). The coordinates must be the measurement in decimal degrees with five decimalaccuracy multiplied by 100,000.

1. Import the required classes.

import net.rim.blackberry.api.invoke.*;

2. Create a class and a constructor to use to invoke BlackBerry Maps.

public class invokeMaps{ public invokeMaps() { }}

3. In the constructor, create an instance of the MapsArguments class. Pass in theMapsArguments.ARG_LOCAL_SEARCH and String objects to represent the search criteria. The following codesample searches for hotels in Waterloo.

MapsArguments ma = new MapsArguments (MapsArguments.ARG_LOCAL_SEARCH, "hotels", "Waterloo");

Development Guide Open BlackBerry Maps by using a local search

87

Page 90: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

4. In the constructor, invoke Invoke.invokeApplication() to open BlackBerry Maps. Pass in theMapsArguments object.

Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, ma);

Code sample: Opening BlackBerry Maps by using a local searchimport net.rim.blackberry.api.invoke.*;

public class invokeMaps{ public invokeMaps() { MapsArguments ma = new MapsArguments (MapsArguments.ARG_LOCAL_SEARCH, "hotels", "Toronto"); Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, ma); }}

Using KML documents with BlackBerry MapsYou can use a KML document to store location information about places, buildings, point of interests, travel paths, bus routes,cycle paths, pictures, and so on. You can create a KML document, publish it on a web site, and view it using BlackBerry® Maps.

For more information about the KML standard, see the complete specification for the OpenGIS® KML Encoding Standard, or theassociated KML Reference.

Supported KML elementsBlackBerry® Maps supports the following KML elements:

KML element Valid children Supported in

kml -- BlackBerry® Java® Development

Environment4.6 or later

Document -- BlackBerry JDE 5.0

address -- BlackBerry JDE 5.0

description -- BlackBerry JDE 5.0

name -- BlackBerry JDE 5.0

phoneNumber -- BlackBerry JDE 5.0

Style Icon, IconStyle, LineStyle, PolyStyle, color,

href, width

BlackBerry JDE 5.0

Development Guide Using KML documents with BlackBerry Maps

88

Page 91: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

KML element Valid children Supported in

Placemark coordinates, Point BlackBerry JDE 4.6

Placemark coordinates, innerBoundaryIs, LinearRing,

LineString, outerBoundaryIs, Point,

Polygon, styleUrl

BlackBerry JDE 5.0

Create a basic KML document

You can create a KML document in any text editor. The XML header and the KML namespace declaration are required and theymust appear at the beginning of the document. You can mark a position on a map in BlackBerry® Maps by using the<Placemark> element. The <Point> element specifies the longitude, latitude, and altitude of the location. Longitude rangesfrom -180 to +180, latitude ranges from -90 to +90. The altitude is optional and can be passed as 0. If you provide an altitude,the value must represent the altitude above sea level in meters.

Code sample: Creating a basic KML document<?xml version="1.0" encoding="UTF-8"?><kml xmlns="http://www.opengis.net/kml/2.2"> <Placemark> <name>Ottawa</name> <description>Ottawa office</description> <Point> <coordinates>-90.86948943473118,48 .25450093195546,0</coordinates> </Point> </Placemark></kml>

Displaying KML overlays on BlackBerry Maps

You can use a KML document to overlay an image at specific locations on a map in BlackBerry® Maps.

In the KML document, the <Folder> element organizes the overlay information. You can use the <GroundOverlay> elementto place an image, that is contained in the <Icon> element, over location on a map. The <LatLonBox> element specifieswhere to position the overlay on the map. You can repeat the <GroundOverlay> element block to specify new overlays andassociated coordinates on the map.

Code sample: Displaying KML overlays on BlackBerry Maps<?xml version="1.0" encoding="UTF-8"?><kml xmlns="http://www.opengis.net/kml/2.2"> <Folder> <name>Pictures</name>

Development Guide Using KML documents with BlackBerry Maps

89

Page 92: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

<visibility>0</visibility> <open>1</open> <GroundOverlay> <name>Glowing</name> <visibility>1</visibility> <description>Hot Spot</description> <Icon> <href>http://www.example.com/picture.png</href> <viewBoundScale>0.75</viewBoundScale> </Icon> <LatLonBox> <north>43.47685828285541</north> <south>43.47485739086753</south> <east>-80.53898253546113</east> <west>-80.54198566880086</west> </LatLonBox> </GroundOverlay> </Folder></kml>

Invoke BlackBerry Maps by using a KML documentYou can invoke BlackBerry® Maps by passing in a MapsArguments object that specifies the URL of a KML document.

Before you begin: Verify that you have created a KML document and published the document to a web site.

1. Import the required classes.

import net.rim.blackberry.api.invoke.*;

2. Create a class and a constructor to use to invoke BlackBerry Maps.

public class invokeMaps{ public invokeMaps() { }}

3. In the constructor, create an instance of the MapsArguments class. Pass in the ARG_KML parameter and the URL of theKML document.

MapsArguments ma = new MapsArguments (MapsArguments.ARG_KML, "http://www.example.com/document.kml");

4. In the constructor, invoke Invoke.invokeApplication() to open BlackBerry Maps. Pass in theMapsArguments object.

Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, ma);

Code sample: Invoking BlackBerry Maps by using a KML document

Development Guide Using KML documents with BlackBerry Maps

90

Page 93: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

import net.rim.blackberry.api.invoke.*;

public class invokeMaps{ public invokeMaps() { MapsArguments ma = new MapsArguments (MapsArguments.ARG_KML, "http://www.example.com/document.kml"); Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, ma); }}

Opening BlackBerry Maps from the BlackBerry BrowserYou can use the BlackBerry® Browser to open BlackBerry® Maps and load a location document. The web server MIME type mustbe correctly configured. Location documents have a MIME type of "text/vnd.rim.location.xloc".

Development Guide Opening BlackBerry Maps from the BlackBerry Browser

91

Page 94: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Custom maps 6

Adding a map to an applicationYou can add a map to an application by using the MapField class and RichMapField class, which are provided in thenet.rim.device.api.lbs.maps.ui package. For example, you can create an application that displays a map that showsthe BlackBerry® device user's current location and points of interest in the surrounding area.

The MapField class extends the net.rim.device.api.ui.Field class. You can use MapField to add the followingfunctionality to your application:

• Rendering a map in a UI field• Panning and zooming the map by using the keyboard, trackpad, trackball, or touch screen

The RichMapField class extends the functionality of MapField. You can use RichMapField to add the following featuresto your application:

• Utility fields on the map, such as a center target, zoom indicator, and a hint field• Fields that overlay a map• Shared focus with other UI components on a screen to allow users to navigate through map field components to other

components on the screen

You can specify the behavior for a map when it displays in a map field by using the methods defined in the MapAction class.For example, when the application opens and displays the map, you can invoke setCentreAndZoom(MapPoint centre,int zoom) to set the center and the zoom level of the map. By default, the center coordinates are (0,0) and the zoom level isset to the maximum value of 15.

You can identify and respond to the actions the user performs in a map field by invoking addChangeListener() to registerthe map field as a listener and then using the constants that are defined in the MapAction class. For example,MapAction.ACTION_ZOOM_CHANGE indicates that the user changed the zoom level.

Each MapField or RichMapField instance uses a thread to render a map. For example, if an application has twoMapField instances running at the same time, two threads are used. The thread ends when the MapField instance is processedfor garbage collection. You should make sure the application does not exceed the limit of available threads. To end the threadfor the MapField or RichMapField instance, you must invoke close(), which removes the field as a listener from specificclasses and allows all appropriate classes to be processed for garbage collection.

Code sample: Adding a map by using the MapField classMapField map = new MapField();add(map);

Code sample: Adding a map by using the RichMapField class

Development Guide Custom maps

92

Page 95: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

RichMapField map = MapFactory.getInstance().generateRichMapField();add(map);

Code sample: Responding to changes in a MapFieldclass MapFieldListener implements FieldChangeListener{ public MapFieldListener () { MapField map = new MapField(); map.addChangeListener(this); }

public void fieldChanged( Field field, int actionId ) { switch ( actionId ) { case MapAction.ACTION_CENTRE_CHANGE: break; case MapAction.ACTION_ZOOM_CHANGE: break; } }}

Add a map to an applicationThe following steps describe how to add a map to a BlackBerry® device application by using the RichMapField class, andhow to set the center and zoom level of the map. The resulting map in the application is shown in the following image:

1. Import the required classes and interfaces.

Development Guide Adding a map to an application

93

Page 96: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

import net.rim.device.api.lbs.maps.*;import net.rim.device.api.lbs.maps.model.*;import net.rim.device.api.lbs.maps.ui.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.container.*;

2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass 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 MapScreen class, which is described in step3, represents the custom screen.

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

3. Create the framework for the custom screen by extending the FullScreen class. In the constructor, invoke super() tocreate a default menu.

class MapScreen extends FullScreen{ public MapScreen() { super( FullScreen.DEFAULT_CLOSE | FullScreen.DEFAULT_MENU ); }}

4. In the screen constructor, invoke MapFactory.getInstance() to create an instance of the MapFactory class andthen invoke generateRichMapField() to generate the RichMapField.

RichMapField map = MapFactory.getInstance().generateRichMapField();

5. In the screen constructor, invoke getAction() to create an instance of the MapAction class. InvokesetCentreAndZoom() to specify the center and zoom level of the map. Invoke add() to add the field to the screen.

MapAction action = map.getAction();action.setCentreAndZoom(new MapPoint(43.47462, -80.53820), 2);add(map);

Development Guide Adding a map to an application

94

Page 97: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Code sample: Adding a map to an application

import net.rim.device.api.lbs.maps.*;import net.rim.device.api.lbs.maps.model.*;import net.rim.device.api.lbs.maps.ui.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.container.*;

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

class MapScreen extends FullScreen{ public MapScreen() { super( FullScreen.DEFAULT_CLOSE | FullScreen.DEFAULT_MENU ); RichMapField map = MapFactory.getInstance().generateRichMapField(); MapAction action = map.getAction(); action.setCentreAndZoom(new MapPoint(43.47462, -80.53820), 2); add(map); }}

Specifying locations on a mapYou can specify a location on a map by using the MapPoint class that is provided in thenet.rim.device.api.lbs.maps.model package. MapPoint represents the geographical coordinates (latitude andlongitude) for a location. You can use MapPoint to focus the map view to display a specific location (for example, you can setthe center location for the map).

Your application can display a marker icon to identify a location on a map by using the MapLocation class. MapLocationis an extension of MapPoint. MapLocation represents the geographical coordinates (latitude and longitude), a label, and adescription for the location and generates a marker icon (a red pushpin) for the location. You can use MapLocation to provide

Development Guide Specifying locations on a map

95

Page 98: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

a point of interest on a map for a specified latitude and longitude (for example, a city). The map displays a marker icon and alabel (for example, "Waterloo") for the location. When the user clicks the location, the description for the location (for example,"This is Waterloo") appears on a separate details screen.

Code sample: Specifying a location by using the MapLocation classMapLocation location = new MapLocation(43.46518, -80.52237, "Waterloo", "This is Waterloo");

Tagging and setting the visibility for locations on a mapYou can assign tags to locations that are stored in a MapDataModel class. Each MapField class has an associatedMapDataModel instance. The MapDataModel class that is provided in the net.rim.device.api.lbs.maps.modelpackage, represents a container. You can add locations and associated data for the locations to the container by invokingMapDataModel.add(). Any item and its associated data are considered mappable items in the container.

You can group mappable items by assigning tags to the items (for example, all work locations have a "work" tag). You can invokeMapDataModel.add() or MapDataModel.tag()to tag mappable items in a MapDataModel container. The add()method allows you to add a mappable item to the container and it allows you to specify a tag for the item. The tag() methodallows you to specify a tag for a single mappable item that is in the container. Multiple locations can have the same tag (forexample, all RIM offices can be tagged "RIM"), and a single location can have multiple tags (for example, a residence can havetags for both "Sarah" and "Paul").

You can specify which tagged items that are stored in MapDataModel are visible or hidden on a map. By default, all items inMapDataModel are visible. For example, you can add the tag "park" to several locations and you can specify that only thelocations with the tag "park" are displayed on the map. You can specify the items that are visible on the map by first invokingMapDataModel.setVisibleNone() to turn off the visibility for all items, and then invokingMapDataModel.setVisible() to turn on the visibility for the specified items.

Development Guide Tagging and setting the visibility for locations on a map

96

Page 99: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Code sample: Tagging locations by using the MapDataModel.add() method

In the following code sample, three locations are defined, and then added and tagged by invoking the MapDataModel.add() method. Only the locations that have a "RIM" tag are visible on the map.

MapDataModel model = map.getModel();MapLocation office01 = new MapLocation( 43.47550, -80.53900, "Head Office", null );MapLocation office02 = new MapLocation( 43.48261, -80.54169, "Manufacturing", null );MapLocation justinHome = new MapLocation( 43.47751, -80.54817, "Justin - Home", null);model.add( (Mappable) office01, "RIM");model.add( (Mappable) office02, "RIM");model.add( (Mappable) justinHome, "home");model.setVisibleNone();model.setVisible( "RIM" );

Tag and set the visibility for locations on a mapThe following steps describe how to assign tags to mappable items that are stored in a MapDataModel class. The visibility isset to display locations that have the "work" tag. The resulting map from the application is shown in the following image:

1. Import the required classes and interfaces.

import net.rim.device.api.lbs.maps.*;import net.rim.device.api.lbs.maps.model.*;import net.rim.device.api.lbs.maps.ui.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.container.*;

2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass 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 MapTagScreen, which is described in step3, represents the custom screen.

Development Guide Tagging and setting the visibility for locations on a map

97

Page 100: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

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

3. Create the framework for the custom screen by extending the FullScreen class. In the constructor, invoke super() tocreate a default menu.

class MapTagScreen extends FullScreen{ public MapTagScreen() { super(FullScreen.DEFAULT_CLOSE | FullScreen.DEFAULT_MENU | FullScreen.VERTICAL_SCROLL | FullScreen.VERTICAL_SCROLLBAR);

4. In the screen constructor, invoke MapFactory.getInstance() to create an instance of the MapFactory class, andthen invoke generateRichMapField() to generate the map field. Invoke add() to add the RichMapField instanceto the screen.

RichMapField map = MapFactory.getInstance().generateRichMapField();add(map);

5. Invoke getModel() to create an instance of the MapDataModel class.

MapDataModel data = map.getModel();

6. Create instances of the MapLocation class to define the locations. Pass the latitude, longitude, label, and description ofeach location to the MapLocation objects.

MapLocation julieHome = new MapLocation( 43.47751, -80.54817, "Julie - Home", null );MapLocation headOffice = new MapLocation( 43.47550, -80.53900, "Head Office", null );

7. Create an integer identifier to represent a mappable item. Assign the mappable item to the identifier by invoking add()to add a location and pass one of the MapLocation objects and a tag for the location to MapDataModel. You can usethe identifier to access the item in MapDataModel and assign another tag to a mappable item by invoking tag(), andpassing as arguments the identifier and the tag. In the following code sample, two locations are added toMapDataModel, and each location is assigned two tags.

Development Guide Tagging and setting the visibility for locations on a map

98

Page 101: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

int julieHomeId = data.add( (Mappable) julieHome, "julie" );data.tag( julieHomeId, "home" );int headOfficeId = data.add( (Mappable) headOffice, "julie" );data.tag( headOfficeId, "work" );

8. Define two more locations, and invoke add() to add the locations to MapDataModel. Invoke tag() to assign theappropriate tags for the locations.

MapLocation paulHome = new MapLocation( 43.49487, -80.55335, "Paul - Home", null );int paulHomeId = data.add( (Mappable) paulHome, "paul" );data.tag( paulHomeId, "home" );data.tag( headOfficeId, "paul" ); data.tag( paulHomeId, "sarah" );MapLocation manufacturing = new MapLocation( 43.46514, -80.50506, "Manufacturing", null );int manufacturingId = data.add( (Mappable) manufacturing, "sarah" );data.tag( manufacturingId, "work" );

9. Turn on visibility for the locations that have the “work” tag. By default, all the locations are visible on the map. InvokesetVisibleNone() to turn the visibility off for all the locations. Invoke setVisible() and pass the "work" tag as anargument to specify that only the locations with the “work” tag are visible on the map.

data.setVisibleNone();data.setVisible( "work" );

10. Invoke getMapField().update() to update the map view. Pass the Boolean value true to the update method torecalculate the center and zoom level of the map with the visible locations on the map.

map.getMapField().update(true);

Code sample: Tagging and setting the visibility for locations on a mapThe following code sample creates a map, assigns tags to multiple locations, and displays only the locations that have a "work" tag.

import net.rim.device.api.ui.*;import net.rim.device.api.ui.container.*;import net.rim.device.api.lbs.maps.*;import net.rim.device.api.lbs.maps.model.*;import net.rim.device.api.lbs.maps.ui.*;

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

Development Guide Tagging and setting the visibility for locations on a map

99

Page 102: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

{ pushScreen(new MapTagScreen()); }}

class MapTagScreen extends FullScreen{ public MapTagScreen() { super(FullScreen.DEFAULT_CLOSE | FullScreen.DEFAULT_MENU | FullScreen.VERTICAL_SCROLL | FullScreen.VERTICAL_SCROLLBAR); RichMapField map = MapFactory.getInstance().generateRichMapField(); add(map); MapDataModel data = map.getModel(); MapLocation julieHome = new MapLocation( 43.47751, -80.54817, "Julie - Home", null ); MapLocation headOffice = new MapLocation( 43.47550, -80.53900, "Head Office", null ); int julieHomeId = data.add( (Mappable) julieHome, "julie" ); data.tag( julieHomeId, "home" ); int headOfficeId = data.add( (Mappable) headOffice, "julie" ); data.tag( headOfficeId, "work" ); MapLocation paulHome = new MapLocation( 43.49487, -80.55335, "Paul - Home", null ); int paulHomeId = data.add( (Mappable) paulHome, "paul" ); data.tag( paulHomeId, "home" ); data.tag( headOfficeId, "paul" ); data.tag( paulHomeId, "sarah" ); MapLocation manufacturing = new MapLocation( 43.46514, -80.50506, "Manufacturing", null ); int manufacturingId = data.add( (Mappable) manufacturing, "sarah" ); data.tag( manufacturingId, "work" ); data.setVisibleNone(); data.setVisible( "work" ); map.getMapField().update( true ); }}

Development Guide

100

Page 103: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Creating a static image of a mapYou can create a static image of a map by invoking MapField.getImage() , which is provided in thenet.rim.device.api.lbs.maps.ui package, or MapFactory.generateStaticImage() , which is provided inthe net.rim.device.api.lbs.maps package.

You can invoke MapField.getImage() to capture an image of the current map view on the screen, including any data thatis visible on the map. MapField.getImage() is used to capture images in UI applications, where the map is a field on thescreen. For example, in an application that displays a map of points of interest, you can provide a button that BlackBerry® deviceusers can click, to save an image of the current map.

You can invoke MapFactory.generateStaticImage() to create an image of a map in the following situations:• To create an image of the current map view on the screen in a non-UI application (for example, in an application that sends

periodic updates of a person’s location to an email address)• To create an image of a map that does not allow user interaction such as panning and zooming (for example, in a contacts

application to provide an image of a map for the contact’s home address)

The generateStaticImage() methods in the MapFactory class provide control over the coordinates for the center andthe zoom level of the image, and calculate the coordinates based on the mappable items that are provided.

Method Description

generateStaticMapImage

(MapDimensions mapProperties,

MappableVector data)

This method uses a MappableVector class and provides the

application with control over the coordinates for the center and the zoom

level of the map image.

generateStaticMapImage

(MapDimensions mapProperties,

MapDataModel data)

This method uses a MapDataModel class and provides the application

with control over the coordinates for the center and the zoom level of the

map image.

generateStaticMapImage(XYDimension

imageSize, MappableVector data)

This method calculates the center and zoom level of the image based on

the mappable data in the MappableVector.

Code sample: Creating a static image of a map in a UI application// add the data to a collectionMapDataModel data = new MapDataModel();data.add( (Mappable) new MapLocation( 43.47550, -80.53900, "Andrew", null ) );data.add( (Mappable) new MapLocation( 43.48261, -80.54169, "Blake", null ) );data.add( (Mappable) new MapLocation( 43.47751, -80.54817, "Christine", null ) );

// create the map and specify the map sizeMapField map = new MapField(data, 200, 200);

Development Guide Creating a static image of a map

101

Page 104: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

// create the imageBitmap image = map.getImage();

Code sample: Creating a static image of a map (map center and zoom level are calculated)// add the data to a collectionMappableVector data = new MappableVector();data.addElement( new MapLocation( 43.47550, -80.53900, "Andrew", null ) );data.addElement( new MapLocation( 43.48261, -80.54169, "Blake", null ) );data.addElement( new MapLocation( 43.47751, -80.54817, "Christine", null ) );

// specify the size of the resulting imageXYDimension imageSize = new XYDimension( 200, 100 ); // create the imageBitmap map = MapFactory.getInstance().generateStaticMapImage( imageSize, data );

Code sample: Creating a static image of a map (map center and zoom level are specified)// add the data to a collectionMapDataModel data = new MapDataModel();MapLocation andrew = new MapLocation(43.47550, -80.53900, "Andrew", null );data.add( (Mappable) andrew );data.add( (Mappable) new MapLocation( 43.48261, -80.54169, "Blake", null ) );data.add( (Mappable) new MapLocation( 43.47751, -80.54817, "Christine", null ) );// visibility for this location is false and it will not display on the mapdata.add( (Mappable) new MapLocation( 43.49487, -80.55335, "Dustin", null), null, false ); // specify the image size, center and zoom levelMapDimensions dim = new MapDimensions( 200, 100 );dim.setCentre( andrew );dim.setZoom( 3 ); // create the imageBitmap map = MapFactory.getInstance().generateStaticMapImage( dim, data );

Adding fields on top of a mapYou can use the RichMapField class to display a map, which can be part of a screen that includes one or more UI components.You can add fields that are not part of the map by invoking RichMapField.add(). The fields are overlays that are not directlyrendered on the map.

Development Guide Adding fields on top of a map

102

Page 105: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

When a RichMapField instance is in a container that contains other UI components (for example, in a dialog box), by default,RichMapField shares focus with the other UI components, which allows a BlackBerry® device user to move fromRichMapField to the other UI components on the screen. If you want to make RichMapField the exclusive field on thescreen (for example, the map is the full screen), you must disable the shared focus by invoking disableOperationMode(MapConstants.MODE_SHARED_FOCUS).

You can use MapConstants.MODE_FOCUS_ACTIVE to specify that RichMapField has focus, and still shares focus withthe other UI components. When RichMapField has focus, RichMapField actively consumes all input events, such as a userclicking the trackpad. Giving focus to RichMapField allows a user to pan and zoom the map without inadvertently exiting themap and moving to other components on the screen. When RichMapField does not have focus, RichMapField does notconsume any input events and a user can pan the map and move focus to another field on the screen.

For more information about UI components, see the BlackBerry Java SDK UI Component Quick Reference Guide.

Code sample: Adding a field on top of a mapRichMapField map = MapFactory.getInstance().generateRichMapField();ButtonField button = new ButtonField( "Click Here", Field.FOCUSABLE); button.setChangeListener( new FieldChangeListener(){ public void fieldChanged( Field field, int context ) { Dialog.alert( "Button clicked." ); }} );map.add( button, 50, 50 );

Code sample: Setting the RichMapField as the exclusive field on the screenRichMapField richMapField = MapFactory.getInstance().generateRichMapField();MapField map = richMapField.getMapField();map.getAction().disableOperationMode( MapConstants.MODE_SHARED_FOCUS );

Related topicsAdding a map to an application, 92

Displaying KML overlays on a mapKML documents are XML-based documents that you can use to store geographic data about places, buildings, points of interest,cycle paths, pictures, and so on. You can create and publish a KML document to a web site. You can display the KML data in amap field by specifying the URL of the KML document in the MapFactory.populateDataModelFromKmlUrl(MapDataModel model, String url, String tag) method.

Development Guide Displaying KML overlays on a map

103

Page 106: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Your application can display KML data in a map field only if the KML document is retrieved through the BlackBerry® InternetService or the BlackBerry® Enterprise Server (for example, a KML document that is stored on a web site or on an intranet site).A KML document that is stored on a BlackBerry device (for example, on a media card) cannot be displayed.

Code sample: Displaying a KML overlayString officeTag = "RIM offices";String officeUrl = "http://www.example.com/rim_offices.kml";

//create the map fieldRichMapField view = MapFactory.getInstance().generateRichMapField();

// retrieve the KML document and populate the data modelMapDataModel model = view.getModel();MapFactory.getInstance().populateDataModelFromKmlUrl( model, officeUrl, officeTag );

// display only the RIM offices and center the view on the visible locationsmodel.setVisibleNone();model.setVisible( officeTag );view.getMapField().update( true );

Related topicsCreate a basic KML document, 89Supported KML elements, 88

Development Guide Displaying KML overlays on a map

104

Page 107: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Navigation 7

Retrieving the estimated travel time and distanceYou can request the estimated time and distance for automobile travel to destinations in the United States and Canada by usingthe Travel Time API, which is provided in the net.rim.device.api.lbs.travel package. For example, you can create asocial networking application that provides the BlackBerry® device user with the estimated time of arrival at a friend's location.

A request for the estimated travel time and distance is forwarded to a Travel Time server, which plots a route between the startingand ending locations. The Travel Time server uses current and historical traffic information to calculate the estimated time anddistance for the trip. You can create a request by creating an instance of the TravelTimeEstimator class and specifyingthe geospatial coordinates for the starting and ending locations, and the starting time of the trip. You can use the current timeor a future time for the starting time of the trip. TravelTimeEstimator is a singleton class that supports synchronous andasynchronous requests.

A synchronous request blocks processes on the current thread until the request returns the travel time and distance estimate orthrows an exception. An asynchronous request returns to the thread after sending a request for an estimate. The results arereturned asynchronously to a caller-provided listener object. You should request the estimated travel time and distanceasynchronously, so that the request does not block the current thread. TravelTimeEstimator returns the results by usingan instance of the TravelTime class.

Retrieve the estimated travel time and distanceYou can create an application that retrieves the estimated time and distance it takes to travel between two locations. In thefollowing steps, a UI application is created that contains a text field in which the BlackBerry® device user types a destinationaddress, a button that the user clicks to retrieve the estimated time and distance to reach the destination, and a field to displaythe 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.*;

Development Guide Navigation

105

Page 108: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass 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 instep 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 traveltime and distance estimate. Invoke Field.setChangeListener() to listen for changes to the button. InvokefindTravelTime(), which is described in step 5, to retrieve the travel time and distance estimate when the user clicksthe button. Invoke add() to add the button to the screen. Create instances of the LabelField class to display the traveltime 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)

Development Guide Retrieving the estimated travel time and distance

106

Page 109: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

{ 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 theString class that invokes getText() to retrieve the destination that the user typed. Validate that the field is not emptyby 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 classin 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. InvokeLandmark.getQualifiedCoordinates() to retrieve the geospatial coordinates for the destination by using thegeolocation service. Invoke LocationProvider.getInstance() to retrieve a location provider to request the currentlocation. Invoke Location.getQualifiedCoordinates() to retrieve the geospatial coordinates for the currentlocation by using GPS. Alternatively, if GPS is unavailable, you can use the geolocation service to retrieve the coordinatesfor 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) {

Development Guide Retrieving the estimated travel time and distance

107

Page 110: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

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 Coordinatesobjects for the starting and ending locations, and specify the starting time. In this example, a synchrous request is madebecause a separate thread was created to retrieve the geospatial coordinates. You can use theTravelTime.START_NOW constant to indicate that travel starts immediately. Invoke showResults(), which isdescribed 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 thedefinition of Runnable. Invoke getElapsedTime() to retrieve the estimated travel time. Convert the returned traveltime from milliseconds to an hour: minute: seconds format. Invoke getDistance() to retrieve the estimated traveldistance. Convert the returned distances from meters to kilometers. Invoke setText() to display the results for the traveltime 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'); }

Development Guide Retrieving the estimated travel time and distance

108

Page 111: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

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

Code sample: Retrieving the estimated travel time and distance

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.*;

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

class TravelTimeScreen extends MainScreen { private BasicEditField _destinationField; private LabelField _timeLabel; private LabelField _distanceLabel; 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,

Development Guide Retrieving the estimated travel time and distance

109

Page 112: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

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

TravelTimeEstimator estimator =

Development Guide Retrieving the estimated travel time and distance

110

Page 113: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

TravelTimeEstimator.getInstance(); final TravelTime travelTime = estimator.requestArrivalEstimate(startPoint, endPoint, TravelTime.START_NOW, null); showResults(travelTime); } catch (final Exception e) { Dialog.alert(e.getMessage()); } } }; travelTimeThread.start(); } 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); }

Development Guide Retrieving the estimated travel time and distance

111

Page 114: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

}); }}

Development Guide Retrieving the estimated travel time and distance

112

Page 115: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Find more information 8

• www.blackberry.com/go/apiref: View the latest version of the API reference for the BlackBerry® Java® SDK.• www.blackberry.com/go/devguides: Find development guides, release notes, and sample application overviews for the

BlackBerry Java SDK.• www.blackberry.com/developers: Visit the BlackBerry® Developer Zone for resources on developing BlackBerry device

applications.• www.blackberry.com/go/developerkb: View knowledge base articles on the BlackBerry Development Knowledge Base.• www.blackberry.com/developers/downloads: Find the latest development tools and downloads for developing BlackBerry

device applications.

Development Guide Find more information

113

Page 116: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Glossary 9

APIapplication programming interface

CDMACode Division Multiple Access

GPSGlobal Positioning System

HTTPHypertext Transfer Protocol

IT policyAn IT policy consists of various IT policy rules that control the security features and behavior of BlackBerry devices, BlackBerryenabled devices, the BlackBerry® Desktop Software, and the BlackBerry® Web Desktop Manager.

JSRJava® Specification Request

KMLKeyhole Markup Language

MIMEMultipurpose Internet Mail Extensions

NMEANational Marine Electronics Association

PDEPosition Determination Entity

WLANwireless local area network

XMLExtensible Markup Language

Development Guide Glossary

114

Page 117: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Provide feedback 10

To provide feedback on this deliverable, visit www.blackberry.com/docsfeedback.

Development Guide Provide feedback

115

Page 118: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Document revision history 11

Date Description

3 September 2010 Changed the following topics:

• Add a map to an application

• Creating a static image of a map

• Tag and set the visibility for locations on a map

• Tagging and setting the visibility for locations on a map

• Code sample: Adding a map to an application

• Code sample: Tagging and setting the visibility for locations on a map

16 August 2010 Added the following topics:

• Add a map to an application

• Adding a map to an application

• Adding fields on top of a map

• Creating a static image of a map

• Displaying KML overlays on a map

• Geolocation overview

• Geolocation modes

• Location-based services overview

• Querying location sources

• Requesting concurrent GPS and geolocation updates

• Retrieve the location of a device by using the geolocation service

• Retrieve the estimated travel time and distance

• Retrieve optimal multiple fixes

• Retrieve the optimal single fix

• Retrieving the location of a device by using the geolocation service

• Retrieving the estimated travel time and distance

• Retrieving the optimal fix with GPS and geolocation

• Specifying locations on a map

• Tag and set the visibility for locations on a map

• Tagging and setting the visibility for locations on a map

Development Guide Document revision history

116

Page 119: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Date Description

• Turning on and querying Location Services on the device

Added the following code samples:

• Code sample: Adding a map to an application

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

• Code sample: Retrieving the estimated travel time and distance

• Code sample: Retrieving the optimal single fix

• Code sample: Retrieving optimal multiple fixes

• Code sample: Tagging and setting the visibility for locations on a map

Changed the following topics:

• Retrieve an address by using reverse geocoding

• Opening BlackBerry Maps from the BlackBerry Browser

Development Guide Document revision history

117

Page 120: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Legal notice 12

©2010 Research In Motion Limited. All rights reserved. BlackBerry®, RIM®, Research In Motion®, SureType®, SurePress™ andrelated trademarks, names, and logos are the property of Research In Motion Limited and are registered and/or used in the U.S.and countries around the world.

Bluetooth is a trademark of Bluetooth SIG. Java, Java ME, Java SE and JavaScript are trademarks of Oracle America, Inc. OpenGISis a trademark of Open Geospatial Consortium, Inc. Wi-Fi is a trademark of the Wi-Fi Alliance. All other trademarks are theproperty of their respective owners.

This documentation including all documentation incorporated by reference herein such as documentation provided or madeavailable at www.blackberry.com/go/docs is provided or made accessible "AS IS" and "AS AVAILABLE" and without condition,endorsement, guarantee, representation, or warranty of any kind by Research In Motion Limited and its affiliated companies("RIM") and RIM assumes no responsibility for any typographical, technical, or other inaccuracies, errors, or omissions in thisdocumentation. In order to protect RIM proprietary and confidential information and/or trade secrets, this documentation maydescribe some aspects of RIM technology in generalized terms. RIM reserves the right to periodically change information thatis contained in this documentation; however, RIM makes no commitment to provide any such changes, updates, enhancements,or other additions to this documentation to you in a timely manner or at all.

This documentation might contain references to third-party sources of information, hardware or software, products or servicesincluding components and content such as content protected by copyright and/or third-party web sites (collectively the "ThirdParty Products and Services"). RIM does not control, and is not responsible for, any Third Party Products and Services including,without limitation the content, accuracy, copyright compliance, compatibility, performance, trustworthiness, legality, decency,links, or any other aspect of Third Party Products and Services. The inclusion of a reference to Third Party Products and Servicesin this documentation does not imply endorsement by RIM of the Third Party Products and Services or the third party in any way.

EXCEPT TO THE EXTENT SPECIFICALLY PROHIBITED BY APPLICABLE LAW IN YOUR JURISDICTION, ALL CONDITIONS,ENDORSEMENTS, GUARANTEES, REPRESENTATIONS, OR WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDINGWITHOUT LIMITATION, ANY CONDITIONS, ENDORSEMENTS, GUARANTEES, REPRESENTATIONS OR WARRANTIES OFDURABILITY, FITNESS FOR A PARTICULAR PURPOSE OR USE, MERCHANTABILITY, MERCHANTABLE QUALITY, NON-INFRINGEMENT, SATISFACTORY QUALITY, OR TITLE, OR ARISING FROM A STATUTE OR CUSTOM OR A COURSE OF DEALINGOR USAGE OF TRADE, OR RELATED TO THE DOCUMENTATION OR ITS USE, OR PERFORMANCE OR NON-PERFORMANCEOF ANY SOFTWARE, HARDWARE, SERVICE, OR ANY THIRD PARTY PRODUCTS AND SERVICES REFERENCED HEREIN, AREHEREBY EXCLUDED. YOU MAY ALSO HAVE OTHER RIGHTS THAT VARY BY STATE OR PROVINCE. SOME JURISDICTIONSMAY NOT ALLOW THE EXCLUSION OR LIMITATION OF IMPLIED WARRANTIES AND CONDITIONS. TO THE EXTENTPERMITTED BY LAW, ANY IMPLIED WARRANTIES OR CONDITIONS RELATING TO THE DOCUMENTATION TO THE EXTENTTHEY CANNOT BE EXCLUDED AS SET OUT ABOVE, BUT CAN BE LIMITED, ARE HEREBY LIMITED TO NINETY (90) DAYS FROMTHE DATE YOU FIRST ACQUIRED THE DOCUMENTATION OR THE ITEM THAT IS THE SUBJECT OF THE CLAIM.

TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW IN YOUR JURISDICTION, IN NO EVENT SHALL RIM BE LIABLEFOR ANY TYPE OF DAMAGES RELATED TO THIS DOCUMENTATION OR ITS USE, OR PERFORMANCE OR NON-PERFORMANCE OF ANY SOFTWARE, HARDWARE, SERVICE, OR ANY THIRD PARTY PRODUCTS AND SERVICES REFERENCEDHEREIN INCLUDING WITHOUT LIMITATION ANY OF THE FOLLOWING DAMAGES: DIRECT, CONSEQUENTIAL, EXEMPLARY,INCIDENTAL, INDIRECT, SPECIAL, PUNITIVE, OR AGGRAVATED DAMAGES, DAMAGES FOR LOSS OF PROFITS OR REVENUES,

Development Guide Legal notice

118

Page 121: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

FAILURE TO REALIZE ANY EXPECTED SAVINGS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, LOSS OFBUSINESS OPPORTUNITY, OR CORRUPTION OR LOSS OF DATA, FAILURES TO TRANSMIT OR RECEIVE ANY DATA, PROBLEMSASSOCIATED WITH ANY APPLICATIONS USED IN CONJUNCTION WITH RIM PRODUCTS OR SERVICES, DOWNTIME COSTS,LOSS OF THE USE OF RIM PRODUCTS OR SERVICES OR ANY PORTION THEREOF OR OF ANY AIRTIME SERVICES, COST OFSUBSTITUTE GOODS, COSTS OF COVER, FACILITIES OR SERVICES, COST OF CAPITAL, OR OTHER SIMILAR PECUNIARYLOSSES, WHETHER OR NOT SUCH DAMAGES WERE FORESEEN OR UNFORESEEN, AND EVEN IF RIM HAS BEEN ADVISEDOF THE POSSIBILITY OF SUCH DAMAGES.

TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW IN YOUR JURISDICTION, RIM SHALL HAVE NO OTHEROBLIGATION, DUTY, OR LIABILITY WHATSOEVER IN CONTRACT, TORT, OR OTHERWISE TO YOU INCLUDING ANY LIABILITYFOR NEGLIGENCE OR STRICT LIABILITY.

THE LIMITATIONS, EXCLUSIONS, AND DISCLAIMERS HEREIN SHALL APPLY: (A) IRRESPECTIVE OF THE NATURE OF THECAUSE OF ACTION, DEMAND, OR ACTION BY YOU INCLUDING BUT NOT LIMITED TO BREACH OF CONTRACT, NEGLIGENCE,TORT, STRICT LIABILITY OR ANY OTHER LEGAL THEORY AND SHALL SURVIVE A FUNDAMENTAL BREACH OR BREACHESOR THE FAILURE OF THE ESSENTIAL PURPOSE OF THIS AGREEMENT OR OF ANY REMEDY CONTAINED HEREIN; AND (B)TO RIM AND ITS AFFILIATED COMPANIES, THEIR SUCCESSORS, ASSIGNS, AGENTS, SUPPLIERS (INCLUDING AIRTIMESERVICE PROVIDERS), AUTHORIZED RIM DISTRIBUTORS (ALSO INCLUDING AIRTIME SERVICE PROVIDERS) AND THEIRRESPECTIVE DIRECTORS, EMPLOYEES, AND INDEPENDENT CONTRACTORS.

IN ADDITION TO THE LIMITATIONS AND EXCLUSIONS SET OUT ABOVE, IN NO EVENT SHALL ANY DIRECTOR, EMPLOYEE,AGENT, DISTRIBUTOR, SUPPLIER, INDEPENDENT CONTRACTOR OF RIM OR ANY AFFILIATES OF RIM HAVE ANY LIABILITYARISING FROM OR RELATED TO THE DOCUMENTATION.

Prior to subscribing for, installing, or using any Third Party Products and Services, it is your responsibility to ensure that yourairtime service provider has agreed to support all of their features. Some airtime service providers might not offer Internet browsingfunctionality with a subscription to the BlackBerry® Internet Service. Check with your service provider for availability, roamingarrangements, service plans and features. Installation or use of Third Party Products and Services with RIM's products and servicesmay require one or more patent, trademark, copyright, or other licenses in order to avoid infringement or violation of third partyrights. You are solely responsible for determining whether to use Third Party Products and Services and if any third party licensesare required to do so. If required you are responsible for acquiring them. You should not install or use Third Party Products andServices until all necessary licenses have been acquired. Any Third Party Products and Services that are provided with RIM'sproducts and services are provided as a convenience to you and are provided "AS IS" with no express or implied conditions,endorsements, guarantees, representations, or warranties of any kind by RIM and RIM assumes no liability whatsoever, in relationthereto. Your use of Third Party Products and Services shall be governed by and subject to you agreeing to the terms of separatelicenses and other agreements applicable thereto with third parties, except to the extent expressly covered by a license or otheragreement with RIM.

Certain features outlined in this documentation require a minimum version of BlackBerry® Enterprise Server, BlackBerry® DesktopSoftware, and/or BlackBerry® Device Software.

The terms of use of any RIM product or service are set out in a separate license or other agreement with RIM applicable thereto.NOTHING IN THIS DOCUMENTATION IS INTENDED TO SUPERSEDE ANY EXPRESS WRITTEN AGREEMENTS OR WARRANTIESPROVIDED BY RIM FOR PORTIONS OF ANY RIM PRODUCT OR SERVICE OTHER THAN THIS DOCUMENTATION.

Research In Motion Limited295 Phillip Street

Development Guide Legal notice

119

Page 122: BlackBerry Java SDK Development Guide 1239071 0730082916 001 6.0 US

Waterloo, ON N2L 3W8Canada

Research In Motion UK Limited Centrum House 36 Station Road Egham, Surrey TW20 9LF United Kingdom

Published in Canada

Development Guide Legal notice

120