BlackBerry Java SDK Location-Based Services Version: 6.0
Development Guide
Published: 2010-09-03 SWD-1239071-0903111352-001
Contents 1
Location-based services overview.............................................................................................................................................
4
2 GPS overview................................................................................................................................................................................ Turning on and querying Location Services on the device........................................................................................................ Querying location sources............................................................................................................................................................. Specifying the GPS mode.............................................................................................................................................................. GPS modes.............................................................................................................................................................................. Specifying the GPS mode by using JSR 179................................................................................................................................. Specify the GPS mode (JSR 179)........................................................................................................................................... Criteria mapping properties.................................................................................................................................................. Specifying the GPS mode by using BlackBerry extensions to JSR 179..................................................................................... Specify the GPS mode by using BlackBerry extensions to JSR 179.................................................................................. Retrieving location information by using the assisted GPS mode............................................................................................ Assisted mode using a PDE server....................................................................................................................................... Verify that PDE server information is required................................................................................................................... Specify the PDE server information..................................................................................................................................... Code sample: Specifying the PDE server information....................................................................................................... Retrieving a location provider....................................................................................................................................................... Retrieve a location provider by using the LocationProvider class.................................................................................... Controlling location tracking by using the BlackBerryLocationProvider class................................................................ Control location tracking by using the BlackBerryLocationProvider class...................................................................... Code sample: Using the BlackBerryLocationProvider class to control location tracking.............................................. Retrieve a location provider by using the BlackBerryLocationProvider class.................................................................. Retrieving the location of a BlackBerry device............................................................................................................................ Retrieve the location of a BlackBerry device....................................................................................................................... Code sample: Retrieving the GPS location of a BlackBerry device.................................................................................. Retrieve the location of a BlackBerry device by specifying continuous fix requests...................................................... Code sample: Retrieving the GPS location of a BlackBerry device by using continuous fix requests......................... Retrieving location information by using the Location class............................................................................................ Retrieve location information by using the Location class................................................................................................ Code sample: Using the Location class to retrieve GPS location information............................................................... Retrieving location information by using the BlackBerryLocation class.......................................................................... Retrieve satellite information by using the BlackBerryLocation class............................................................................. Code sample: Using the BlackBerryLocation class to retrieve satellite information.....................................................
5 6 7 8 8 9 9 10 11 12 13 13 13 14 15 16 17 19 19 21 23 24 24 25 26 27 28 29 30 32 32 34
Change the criteria to receive location information.......................................................................................................... Code sample: Changing the criteria to retrieve location information............................................................................. Error handling.................................................................................................................................................................................. Handle errors (JSR 179)......................................................................................................................................................... Handle errors (BlackBerry extensions to JSR 179).............................................................................................................. Retrieve a GPS location by using a web page............................................................................................................................. Retrieving a GPS location by using a web page.................................................................................................................
35 37 39 39 40 42 44
3 Geolocation overview.................................................................................................................................................................. Geolocation modes......................................................................................................................................................................... Retrieving the location of a device by using the geolocation service....................................................................................... Retrieve the location of a device by using the geolocation service.................................................................................. Code sample: Retrieving the location of a device by using the geolocation service..................................................... Retrieving the optimal fix with GPS and geolocation................................................................................................................. Retrieve the optimal single fix.............................................................................................................................................. Code sample: Retrieving the optimal single fix.................................................................................................................. Retrieve optimal multiple fixes............................................................................................................................................. Code sample: Retrieving optimal multiple fixes................................................................................................................. Requesting concurrent GPS and geolocation updates..............................................................................................................
46 46 47 47 51 54 54 58 61 65 68
4 Geocoding and reverse geocoding........................................................................................................................................... Retrieve geospatial coordinates for an address by using geocoding....................................................................................... Retrieve an address by using reverse geocoding........................................................................................................................ Code sample: Retrieving an address by using geospatial coordinates and reverse geocoding............................................
69 69 71 73
5 BlackBerry Maps.......................................................................................................................................................................... Opening BlackBerry Maps from your application....................................................................................................................... Open BlackBerry Maps by using the default settings................................................................................................................ Open BlackBerry Maps by using information from a contact................................................................................................... Open BlackBerry Maps by using specific coordinates................................................................................................................ Open BlackBerry Maps by using a landmark............................................................................................................................... Opening BlackBerry Maps by using a location document......................................................................................................... XML element: <lbs>................................................................................................................................................................ XML element: <location>....................................................................................................................................................... XML element: <getRoute>..................................................................................................................................................... Display and clear locations on a map by using a location document..............................................................................
74 74 74 75 77 78 80 80 81 83 83
Display and clear a route on a map by using a location document................................................................................. Open BlackBerry Maps by using a local search.......................................................................................................................... Using KML documents with BlackBerry Maps............................................................................................................................ Supported KML elements...................................................................................................................................................... Create a basic KML document.............................................................................................................................................. Displaying KML overlays on BlackBerry Maps.................................................................................................................... Invoke BlackBerry Maps by using a KML document.......................................................................................................... Opening BlackBerry Maps from the BlackBerry Browser...........................................................................................................
85 87 88 88 89 89 90 91
6 Custom maps................................................................................................................................................................................ Adding a map to an application.................................................................................................................................................... Add a map to an application................................................................................................................................................. Code sample: Adding a map to an application................................................................................................................... Specifying locations on a map....................................................................................................................................................... Tagging and setting the visibility for locations on a map.......................................................................................................... Tag and set the visibility for locations on a map................................................................................................................ Code sample: Tagging and setting the visibility for locations on a map......................................................................... Creating a static image of a map.................................................................................................................................................. Adding fields on top of a map....................................................................................................................................................... Displaying KML overlays on a map...............................................................................................................................................
92 92 93 95 95 96 97 99 101 102 103
7 Navigation.................................................................................................................................................................................... Retrieving the estimated travel time and distance..................................................................................................................... Retrieve the estimated travel time and distance................................................................................................................ Code sample: Retrieving the estimated travel time and distance....................................................................................
105 105 105 109
8 Find more information................................................................................................................................................................
113
9 Glossary.........................................................................................................................................................................................
114
10 Provide feedback.........................................................................................................................................................................
115
11 Document revision history.........................................................................................................................................................
116
12 Legal notice..................................................................................................................................................................................
118
Development Guide
Location-based services overview
Location-based services overview
1
You can create location and maps-based applications for BlackBerry® devices by using the Location-Based Services APIs that the BlackBerry® Java® SDK provides. You can use these APIs to retrieve the location of a BlackBerry device, display location information 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 build a 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 images of a map. To provide navigation information, such as the estimated time of arrival, you can use the Travel Time API that is provided in the net.rim.device.api.lbs.travel package. The Travel Time API uses current and historical traffic data to provide an estimate for the total travel time and distance for automobile travel to destinations in the United States and Canada.
4
Development Guide
GPS overview
GPS overview
2
You can allow a BlackBerry® device application to retrieve the GPS location of a BlackBerry device. The values for the location information 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 of a GPS fix and the level of location accuracy. For example, a weather application might specify a cell site mode, which can quickly provide an approximate location. For more information about the BlackBerry device models and their available corresponding GPS 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 the javax.microedition.location package, or the BlackBerry extension to JSR 179 in the net.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 */
5
Development Guide
Turning on and querying Location Services on the device
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 device The Location Services option on the BlackBerry® device controls the availability of location data. When the Location Services option is turned on, you can retrieve location information from any available location source (internal GPS receiver, external GPS receiver, 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 provided in the net.rim.device.api.gps package. If the option is not turned on, you can programmatically turn it on by invoking LocationInfo.setLocationOn(). To turn on the Location Services option, your application must be signed and it must have permission to change the settings on the device. Make sure your application prompts the BlackBerry device user for permission 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 the device 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 is enabled, the IT policy on the BlackBerry Enterprise Server permits access to the geolocation service, and the wireless service provider permits access to the service • For external GPS receivers, location data becomes available if the external receiver is specified as the current GPS Data Source (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.
6
Querying location sources
Development Guide
Querying location sources Location data can be retrieved by using various location sources, such as an internal GPS receiver, an external GPS receiver, or a 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 but might 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 the following 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 the net.rim.device.api.gps.LocationInfo class: Method
Description
getSupportedLocationSources()
This method returns an integer mask that represents the location sources that the device supports. This method returns a value of true if the source you specify is supported on the device. 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. This method returns a value of true if the mode you specify is available to provide location information.
isLocationSourceSupported(int mode) getAvailableLocationSources()
isLocationSourceAvailable(int mode)
7
Specifying the GPS mode
Development Guide
Code sample: Verifying whether location sources are supported int locationCapability = LocationInfo.getSupportedLocationSources(); boolean gps = (locationCapability & (GPSInfo.GPS_DEVICE_INTERNAL | GPSInfo.GPS_DEVICE_BLUETOOTH)) != 0
Code sample: Verifying whether any location sources are available if (LocationInfo.getAvailableLocationSources() != 0)
Specifying the GPS mode You must specify the GPS mode to retrieve the location of a BlackBerry® device. GPS modes include autonomous, assisted and cell 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 modes Your BlackBerry® device application must verify that a GPS mode is available for use on each BlackBerry device that your application 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. 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. This mode uses the wireless network to retrieve satellite information. This mode can achieve a fast retrieval of the first GPS fix. 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.
autonomous
assisted MS-based
8
Specifying the GPS mode by using JSR 179
Development Guide
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. 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. 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. 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. 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.
speed optimal
accuracy optimal
data optimal
Bluetooth® enabled GPS
Specifying the GPS mode by using JSR 179 If you use the JSR 179 package, you must specify the properties for the GPS mode in the javax.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 used regardless 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()
9
Specifying the GPS mode by using JSR 179
Development Guide
}
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 properties If you use the JSR 179 Location API for to specify a GPS mode, you must map the following properties for the Criteria class.
GPS mode
Horizontal accuracy
Vertical accuracy
Cost allowed
Power usage level
Response time Fix frequency
Autonomous
required
required
no
any
any
Autonomous
not required
not required
no
any
Assisted or data optimal
not required
not required
yes
medium, high, or not required medium, high, or not required
10
any
single or multiple single or multiple single or multiple
Specifying the GPS mode by using BlackBerry extensions to JSR 179
Development Guide
GPS mode Assisted or speed optimal Assisted or MSBased Assisted or accuracy optimal Assisted or MSAssisted Cell site
Horizontal accuracy
Vertical accuracy
Cost allowed
Power usage level
required
required
yes
high
required
required
yes
required
required
yes
medium or not required high
required
required
yes
not required
not required
yes
medium or not required low
Response time Fix frequency quality of service quality of service quality of service
multiple
quality of service any
single
multiple single
any
Specifying the GPS mode by using BlackBerry extensions to JSR 179 The BlackBerry速 extensions to JSR 179 provide an enhanced set of GPS criteria. The net.rim.device.api.gps.BlackBerryCriteria class extends the javax.microedition.location.Criteria class. You can use the methods in the BlackBerryCriteria class to specify 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. 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. You can use this method to specify a subsequent GPS mode to use after a successful first GPS fix is retrieved. 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.
setFailoverMode (int, int, int)
setSubsequentMode (int) setGPSRestartInterval (int, int)
11
Specifying the GPS mode by using BlackBerry extensions to JSR 179
Development Guide
Method
Description
setSatelliteInfoRequired
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.
(boolean, boolean)
Specify the GPS mode by using BlackBerry extensions to JSR 179 The 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;
}
3.
public handleGPS() { }
In the constructor, create a try/catch block. In this block, create an instance of the BlackBerryCriteria class by passing 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 you specify cannot retrieve a GPS fix. Invoke setSubsequentMode() to specify a subsequent GPS mode to use after a successful first fix is retrieved. myCriteria.setFailoverMode(GPSInfo.GPS_MODE_AUTONOMOUS, 3, 100); myCriteria.setSubsequentMode(GPSInfo.GPS_MODE_AUTONOMOUS);
5.
12
To verify if a GPS mode is supported, invoke GPSInfo.isGPSModeAvailable() and pass the GPS mode as a parameter. Invoke setMode() to specify the GPS mode, if the mode is supported.
Retrieving location information by using the assisted GPS mode
Development Guide
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 server technology. 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 formal relationship with wireless service providers before you can connect to their PDE server.
Verify that PDE server information is required Before 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 the PDE server information to use assisted mode. public class checkPDE { public checkPDE() { if ( isPDEInfoRequired(GPSInfo.GPS_MODE_ASSIST)) { // set up PDE server access } } }
13
Development Guide
Retrieving location information by using the assisted GPS mode
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;
}
3.
public handleGPS() { }
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 a parameter to determine if the assisted mode is available on the BlackBerry速 device. Invoke isPDEInfoRequired() to determine if you need to specify PDE server information. If PDE server information is required, create an instance of the BlackBerryCriteria 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);
14
Retrieving location information by using the assisted GPS mode
Development Guide
6.
In the run() method of the private class, create a try/catch block. In the block, associate an instance of the BlackBerryCriteria 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. Invoke setPDEInfo()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 {
15
Retrieving a location provider
Development Guide
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 provider After you specify the GPS mode, you must retrieve the location provider that your application uses to support the GPS mode. A location provider represents the source of the location information and it works based on given criteria (for example, the horizontal accuracy and the power usage) .
16
Development Guide
Retrieving a location provider
If the application uses the Criteria class from the JSR 179 package to specify a GPS mode, then the application must retrieve an instance of the LocationProvider class. If the application uses the BlackBerryCriteria class, then the application must retrieve an instance of the BlackBerryLocationProvider class. A BlackBerryLocationProvider object extends the javax.microedition.location.LocationProvider class. 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 ready state while also in a paused state.
Retrieve a location provider by using the LocationProvider class 1.
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, autonomous mode 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);
17
Retrieving a location provider
Development Guide
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 invoking getInstance(). try {
LocationProvider myProvider = LocationProvider.getInstance(myCriteria);
} catch ( LocationException lex ) { return; }
Code sample: Retrieving a location provider by using the LocationProvider class import 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
18
Retrieving a location provider
Development Guide
}
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 the javax.microedition.location.LocationProvider class and it is required for BlackBerry速 device applications that use the BlackBerry extensions to JSR 179. You can use the methods that are provided in the BlackBerryLocationProvider 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. 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. This method resumes location tracking after it is in a paused state. 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.
pauseLocationTracking (int interval)
resumeLocationTracking() stopLocationTracking()
Control location tracking by using the BlackBerryLocationProvider class You can pause, resume, and stop location tracking by using the net.rim.device.api.gps.BlackBerryLocationProvider class.
1.
Import the required classes.
19
Development Guide
Retrieving a location provider
import net.rim.device.api.gps.*; import javax.microedition.location.*;
2.
Create a new class and a constructor. public class handleGPS { static BlackBerryLocationProvider myProvider;
}
3.
public handleGPS() { }
In the constructor, create a try/catch block. In the block, create an instance of the BlackBerryCriteria class by passing 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 the BlackBerryLocationProvider class by retrieving an instance of the BlackBerryCriteria class. Invoke setLocationListener() by passing the interval value, timeout value, and maximum age as parameters to add a LocationListener. 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.
20
Outside of the try/catch block, invoke pauseLocationTracking(), resumeLocationTracking(), or stopLocationTracking() to pause, resume, or stop location tracking.
Retrieving a location provider
Development Guide
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);
21
Retrieving a location provider
Development Guide
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 } }
}
22
}
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
Retrieve a location provider by using the BlackBerryLocationProvider class 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 BlackBerryCriteria myCriteria;
}
3.
public handleGPS() { }
In the constructor, create a try/catch block. In the block, create an instance of the BlackBerryCriteria class and pass the GPS mode to the constructor. Create a second try/catch block, then create an instance of the BlackBerryLocationProvider class by invoking getInstance() to retrieve an instance of the BlackBerryCriteria object. try
{
myCriteria = new BlackBerryCriteria(GPSInfo.GPS_MODE_ASSIST); try {
BlackBerryLocationProvider myProvider = (BlackBerryLocationProvider) LocationProvider.getInstance(myCriteria);
} catch ( LocationException lex ) { return; }
}
}
} catch ( UnsupportedOperationException ex ) { return; }
23
Development Guide
Retrieving the location of a BlackBerry device
Retrieving the location of a BlackBerry device You can retrieve the location of a BlackBerry速 device by specifying a single GPS fix, or by specifying a location listener to retrieve continuous GPS fixes.
Retrieve the location of a BlackBerry device 1.
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 that the autonomous mode. Criteria myCriteria = new Criteria(); myCriteria.setCostAllowed(false);
24
Retrieving the location of a BlackBerry device
Development Guide
7.
In the run() method, create a try/catch block. In the block create a LocationProvider object by getting an instance of the Criteria object. Create another try/catch block to create a Location object to request the current location 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 {
25
Retrieving the location of a BlackBerry device
Development Guide
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 requests You 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() { } }
26
Development Guide
3.
Retrieving the location of a BlackBerry device
In the constructor, create an instance of the Criteria class. Create a try/catch block. In this block, create an instance of the LocationProvider class by invoking getInstance() and using the Criteria object. Invoke setLocationListener() 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 fix requests import javax.microedition.location.*; public class handleGPS { public handleGPS()
27
Retrieving the location of a BlackBerry device
Development Guide
{
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, to retrieve the following information: • •
28
latitude as a double longitude as a double
Retrieving the location of a BlackBerry device
Development Guide
• • • •
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 class You can request a GPS fix and then retrieve the latitude, longitude, velocity, course heading, time stamp, and the number of satellites that the BlackBerry® device is tracking. 1.
Import the required classes. import javax.microedition.location.*;
2.
Create a class and a constructor. public class handleGPS { public handleGPS() { } }
3.
In the class, declare static fields for a thread and for each item of location information that you retrieve. static static static static static static static
4.
GPSThread gpsThread; double latitude; double longitude; float heading; float velocity; long timeStamp; String nmeaString;
In the constructor, create and start a thread. gpsThread = new GPSThread(); gpsThread.start();
5.
In the class, create a private static class that extends Thread, and create a run() method. private static class GPSThread extends Thread { public void run() { } }
6.
In run(), create an instance of the Criteria class. Invoke setCostAllowed(false) to specify the autonomous mode.
29
Development Guide
Retrieving the location of a BlackBerry device
Criteria myCriteria = new Criteria(); myCriteria.setCostAllowed(false);
7.
In run(), create a try/catch block. In this block create an instance of the LocationProvider class by getting an instance of the Criteria object. Create a try/catch block within this block, and create an instance of the Location class to retrieve the current GPS fix including a 300 second timeout expiry. Populate the fields, and specify the number of satellites by invoking getExtraInfo("application/X-jsr179-location-nmea"). try {
LocationProvider myLocationProvider = LocationProvider.getInstance(myCriteria); try { Location myLocation = myLocationProvider.getLocation(300); latitude = myLocation.getQualifiedCoordinates().getLatitude(); longitude = myLocation.getQualifiedCoordinates().getLongitude(); velocity = myLocation.getSpeed(); heading = myLocation.getCourse(); timeStamp = myLocation.getTimestamp(); nmeaString = myLocation.getExtraInfo ("application/X-jsr179-location-nmea");
} catch ( InterruptedException iex ) {} catch ( LocationException lex ) {}
} catch ( LocationException lex ) {} return;
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;
30
Retrieving the location of a BlackBerry device
Development Guide
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;
31
Retrieving the location of a BlackBerry device
Development Guide
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 the BlackBerryLocation 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 class You can request a GPS fix and then retrieve the current number of satellites in view, tracked satellites, average satellite signal quality, 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 static static static static
4.
GPSThread gpsThread; int satCount; int signalQuality; int dataSource; int gpsMode;
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()
32
Retrieving the location of a BlackBerry device
Development Guide
}
6.
{ }
In run(), create a try/catch block. In this block, create an instance of the BlackBerryCriteria class that specifies the GPS mode. Create a second try/catch block. In this block create an instance of the BlackBerryLocationProvider class by getting an instance of the BlackBerryCriteria object. try {
BlackBerryCriteria myCriteria = new BlackBerryCriteria(GPSInfo.GPS_MODE_AUTONOMOUS); try {
7.
BlackBerryLocationProvider myProvider = (BlackBerryLocationProvider)LocationProvider.getInstance(myCriteria);
Create a third try/catch block that is in the first try/catch block. Create a BlackBerryLocation object to retrieve the GPS fix including a 300 second timeout expiry. Populate the fields and extract the satellite information into a StringBuffer 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 ) {}
33
Retrieving the location of a BlackBerry device
Development Guide
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 = ":";
34
Retrieving the location of a BlackBerry device
Development Guide
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 information You can use an instance of the LocationProvider class to automatically change the criteria that is used to track the location of 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)
35
Development Guide
{ }
}
3.
Retrieving the location of a BlackBerry device
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 location tracking. Invoke reset() on the LocationProvider object, and then set the location listener to null to disable the listener. 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 the constructor. 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 by invoking getInstance() and passing the Criteria object as a parameter. Specify a location listener to handle the GPS location updates. try {
locationProvider = LocationProvider.getInstance(myCriteria); if (locationProvider != null) { locationProvider.setLocationListener (new myLocationListener(), -1, -1, -1);
36
Development Guide
Retrieving the location of a BlackBerry device
} } catch (Exception err) {}
7.
In the class, create a private static class that implements the LocationListener interface. Retrieve the current location information 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);
37
Development Guide
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(); }
}
38
}
public void providerStateChanged(LocationProvider provider, int newState) { }
Development Guide
Error handling
Error handling You 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速 extensions to 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; }
39
Development Guide
Error handling
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 invoking BlackBerryLocation.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 by passing 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 the BlackBerryLocationProvider class by retrieving the BlackBerryCriteria object. Invoke setLocationListener() 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() and providerStateChanged().
40
Error handling
Development Guide
private static class myLocationListener implements LocationListener { public void locationUpdated(LocationProvider provider, Location location) { }
}
6.
public void providerStateChanged(LocationProvider provider, int newState) { }
In locationUpdated(), verify if the location parameter is an instance of BlackBerryLocation. If so, then create a local BlackBerryLocation object by passing the location parameter. Invoke getStatus() to retrieve the 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 case case case }
BlackBerryLocation.FAILOVER_MODE_ON: BlackBerryLocation.SUBSEQUENT_MODE_ON: BlackBerryLocation.GPS_FIX_PARTIAL: 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)
41
Retrieve a GPS location by using a web page
Development Guide
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 case case case
}
}
}
}
}
BlackBerryLocation.FAILOVER_MODE_ON: BlackBerryLocation.SUBSEQUENT_MODE_ON: BlackBerryLocation.GPS_FIX_PARTIAL: BlackBerryLocation.GPS_FIX_COMPLETE: break;
public void providerStateChanged (LocationProvider provider, int newState) { }
Retrieve a GPS location by using a web page
42
Development Guide
Retrieve a GPS location by using a web page
The following code sample demonstrates how to determine if a web page was loaded by the BlackBerry速 Browser and if the BlackBerry device supports GPS functionality. If these conditions are true, the web page receives the updated location information to 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>
43
Retrieve a GPS location by using a web page
Development Guide
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 the BlackBerry® 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. This property returns the current latitude, in degrees, of the BlackBerry device. Positive values indicate northern latitude, negative values indicate southern latitude. This property returns the current longitude, in degrees, of the BlackBerry device. Positive values indicate eastern longitude, negative values indicate western longitude This property returns time (in milliseconds since epoch) at which the blackberry .location object was updated.
blackberry .location .latitude
blackberry .location .longitude
blackberry .location .timestamp
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: • • •
blackberry .location .refreshLocation ()
44
0 for Cell Site mode 1 for Assisted mode 2 for Autonomous mode
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
Retrieve a GPS location by using a web page
Development Guide
JavaScript method
blackberry .location .onLocationUpdate ("callback")
Description reads blackberry .location .latitude and blackberry .location .longitude, and then call refreshLocation() afterwards. 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.
blackberry .location .removeLocationUpd ate ()
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. 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.
45
Geolocation overview
Development Guide
Geolocation overview
3
The geolocation service provides an approximate location of the BlackBerry® device by using cell tower positioning and WLAN access points. The approximate location is within 200 meters to 5 kilometers of the location of the device when cell tower positioning is used, and 30 to 500 meters when WLAN access points are used. GPS technology is not required on the device for your application to use the geolocation service, so it is ideal for applications that require only an approximate location and that are used indoors (for example, applications that recommend local points of interest). When you retrieve location information from the geolocation service, the cell tower and WLAN access points information is stored locally on the device. The next time you try to retrieve location information, the cache is checked first and if the location is the same, the data is returned from the cache. Accessing the cache helps to minimize bandwidth usage and provide faster responses. Access to the geolocation service can be controlled by the BlackBerry device user in the options on the device, by an IT policy on the BlackBerry® Enterprise Server, or by the wireless service provider. Cell tower geolocation is supported on devices that run BlackBerry® Device Software 5.0 or later. Geolocation using WLAN access points is supported on BlackBerry devices that run BlackBerry Device Software 6.0 or later.
Geolocation modes With BlackBerry® Java® SDK 6.0 and later, you can retrieve geolocation information by specifying one of the following modes that are provided in the LocationInfo class ( net.rim.device.api.gps package): Mode
Description
GEOLOCATION_MODE
This mode retrieves a location from among the currently available geolocation sources, based on factors such as network connectivity, location accuracy, and data availability. This mode retrieves a location based on cell tower positioning. This mode retrieves a location based on WLAN access points positioning.
GEOLOCATION_MODE_CELL GEOLOCATION_MODE_WLAN
If you specify the GEOLOCATION_MODE or the GEOLOCATION_MODE_CELL mode and the BlackBerry device does not support geolocation, the location is obtained using the cell site mode that is provided by the wireless service provider. Cell site geolocation might 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 tower positioning. To retrieve a location by using geolocation, you must specify GPSInfo.GPS_MODE_CELLSITE as the mode.
46
Development Guide
Retrieving the location of a device by using the geolocation service
Retrieving the location of a device by using the geolocation service You can use the geolocation service to retrieve the location of a BlackBerry® device by performing the following actions (which are similar to the actions involved in retrieving a GPS location): 1. 2. 3. 4.
Specify a geolocation mode in a BlackBerryCriteria object. Retrieve a location provider. Request a single geolocation fix or multiple geolocation fixes. Retrieve the location information for the device.
Code sample: Specifying a geolocation mode BlackBerryCriteria myCriteria = new BlackBerryCriteria(LocationInfo.GEOLOCATION_MODE);
Code sample: Retrieving a location provider BlackBerryLocationProvider myProvider = (BlackBerryLocationProvider)LocationProvider.getInstance(myCriteria);
Code sample: Requesting a single geolocation fix or multiple geolocation fixes /* Single location fix */ BlackBerryLocation myLocation = myProvider.getLocation(timeout); /* Multiple location fixes */ myProvider.setLocationListener(…);
Code sample: Retrieving the location information for the device double lat = myLocation.getQualifiedCoordinates().getLatitude(); double lng = myLocation.getQualifiedCoordinates().getLongitude(); double alt = myLocation.getQualifiedCoordinates().getAltitude();
Retrieve the location of a device by using the geolocation service The following steps demonstrate how to create a UI application that provides the location of the BlackBerry® device by using the geolocation service. Before you begin: Verify that the BlackBerry device or BlackBerry Smartphone Simulator can access the geolocation service. 1.
Import the required classes and interfaces. import net.rim.device.api.gps.*; import net.rim.device.api.system.Application; import net.rim.device.api.ui.*;
47
Development Guide
Retrieving the location of a device by using the geolocation service
import net.rim.device.api.ui.component.*; import net.rim.device.api.ui.container.*; import javax.microedition.location.*;
2.
Create the application framework by extending the UiApplication class. In main(), create an instance of the new class and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor, invoke pushScreen() to display the custom screen for the application. The GeolocationScreen class, which is described in step 3, represents the custom screen. public final class GeolocationDemo extends UiApplication { public static void main(String[] args) { GeolocationDemo theApp = new GeolocationDemo(); theApp.enterEventDispatcher(); }
}
3.
public GeolocationDemo() { pushScreen(new GeolocationScreen()); }
Create the framework for the custom screen by extending the MainScreen class. Create an instance of the LabelField class to store the coordinates that display on the screen. Create two double variables to store the latitude and longitude values. class GeolocationScreen extends MainScreen { private LabelField _coordLabel; private double _latitude; private double _longitude; }
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.
48
In the screen constructor, create an instance of the ButtonField class to create a button that the BlackBerry device user clicks to retrieve the geolocation of the device. Invoke Field.setChangeListener() to listen for changes to the button. Invoke findGeolocation(), which is described in step 6, to retrieve the geolocation when the user clicks the button. Invoke add() to add the button to the screen. Create an instance of the LabelField class to display the resulting coordinates and invoke add() to add the field to the screen.
Development Guide
Retrieving the location of a device by using the geolocation service
ButtonField geolocButton = new ButtonField("Get geolocation", ButtonField.CONSUME_CLICK); geolocButton.setChangeListener(new FieldChangeListener() { public void fieldChanged(Field field, int context) { findGeolocation(); } }); add(geolocButton); this._coordLabel = new LabelField(); add(this._coordLabel);
6.
Create the framework for the findGeolocation method. Invoke setText() with an empty String value to clear LabelField for the coordinates. Create an instance of the Thread class that invokes run(). This thread is used to process the retrieval of the geolocation information. In run(), create a try/catch block to specify the geolocation mode. Create an instance of the BlackBerryCriteria class by invoking BlackBerryCriteria() and pass LocationInfo.GEOLOCATION_MODE as the mode to retrieve geolocation information. In the catch block, invoke showException(), which is described in step 10, to display the error message for an UnsupportedOperationException. private void findGeolocation() { this._coordLabel.setText("");
}
7.
Thread geolocThread = new Thread() { public void run() { try { BlackBerryCriteria myCriteria = new BlackBerryCriteria(LocationInfo.GEOLOCATION_MODE); } catch (UnsupportedOperationException e) { showException(e); } } }; geolocThread.start();
In the first try block, create a second try/catch block to retrieve a location provider. Invoke LocationProvider.getInstance() with the BlackBerryCriteria object to retrieve a location provider. In the catch block, invoke showException(), which is described in step 10, to display the error message for a LocationException.
49
Development Guide
try {
Retrieving the location of a device by using the geolocation service
BlackBerryLocationProvider myProvider = (BlackBerryLocationProvider)LocationProvider.getInstance(myCriteria);
} catch (LocationException e) { showException(e); }
8.
In the second try block, create a third try/catch block to retrieve the location information. Invoke BlackBerryLocationProvider.getLocation() with a parameter of -1 to retrieve a location provider by using the default timeout value. Invoke getLongitude() and getLatitude() to retrieve the longitudinal and latitudinal coordinates respectively. Create an instance of the StringBuffer class and append the resulting coordinates to the buffer. Create a String variable and invoke toString() with the StringBuffer object to return the String value for the coordinates. Invoke showResults()to display the results on the screen, which is described in step 9. In the first catch block, invoke showException(), which is described in step 10, to display the error message for an InterruptedException. In the second catch block, invoke showException(), which is described in step 10, to display the error message for a LocationException. try {
BlackBerryLocation myLocation =(BlackBerryLocation)myProvider.getLocation(-1); _longitude = myLocation.getQualifiedCoordinates().getLongitude(); _latitude = myLocation.getQualifiedCoordinates().getLatitude(); StringBuffer sb = new StringBuffer(); sb.append("Longitude: "); sb.append(_longitude); sb.append("\n"); sb.append("Latitude: "); sb.append(_latitude); String msg = sb.toString(); showResults(msg);
} catch (InterruptedException e) { showException(e); } catch (LocationException e) { showException(e); }
9.
50
In the showResults method, invoke invokeLater() to add this section of code to the event queue of the application. Create an instance of the Runnable class and pass it as a parameter to invokeLater(). Override run() in the definition of Runnable. Invoke setText() with the String variable to specify the resulting coordinates for the LabelField.
Development Guide
Retrieving the location of a device by using the geolocation service
private void showResults(final String msg) { Application.getApplication().invokeLater(new Runnable() { public void run() { GeolocationScreen.this._coordLabel.setText(msg); } }); }
10. In the showException method, invoke invokeLater() to add this section of code to the event queue of the application. Create an instance of Runnable and pass it as a parameter to invokeLater(). Override run() in the definition of Runnable. Invoke Dialog.alert() to create an alert dialog box, and pass the error message by invoking getMessage (). private void showException(final Exception e) { Application.getApplication().invokeLater(new Runnable() { public void run() { Dialog.alert(e.getMessage()); } }); }
Code sample: Retrieving the location of a device by using the geolocation service The following code sample demonstrates how to create a UI application that provides the location of the BlackBerry速 device by using the geolocation service. import import import import import import
net.rim.device.api.gps.*; net.rim.device.api.system.Application; net.rim.device.api.ui.*; net.rim.device.api.ui.container.*; net.rim.device.api.ui.component.*; 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());
51
Development Guide
}
Retrieving the location of a device by using the geolocation service
}
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 =
52
Retrieving the location of a device by using the geolocation service
Development Guide
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()
53
Retrieving the optimal fix with GPS and geolocation
Development Guide
{
}
}
});
}
Dialog.alert(e.getMessage());
Retrieving the optimal fix with GPS and geolocation You can retrieve the optimal location fix by requesting geolocation updates along with GPS updates. An optimal fix provides a geolocation fix when a GPS fix cannot be retrieved during the specified timeout period. You can use this request in an application that 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 for retrieving 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. 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.
enableGeolocationWithGPS (BlackBerryCriteria.FASTES T_FIX_PREFERRED)
Retrieve the optimal single fix The following steps demonstrate how to create a UI application that provides the fastest available location fix, which may come from a geolocation or GPS location source. The location coordinates and the mode that the application uses to retrieve the location 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 import import import import import
54
net.rim.device.api.gps.*; net.rim.device.api.system.Application; net.rim.device.api.ui.*; net.rim.device.api.ui.component.*; net.rim.device.api.ui.container.*; javax.microedition.location.*;
Development Guide
2.
Retrieving the optimal fix with GPS and geolocation
Create the application framework by extending the UiApplication class. In main(), create an instance of the new class and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor, invoke pushScreen() to display the custom screen for the application. The SingleFixScreen class, which is described in step 3, represents the custom screen. public final class SingleFixDemo extends UiApplication { public static void main(String[] args) { SingleFixDemo theApp = new SingleFixDemo(); theApp.enterEventDispatcher(); }
}
3.
public SingleFixDemo() { pushScreen(new SingleFixScreen()); }
Create the framework for the custom screen by extending the MainScreen class. Create an instance of the LabelField class to store the coordinates that you want to display on the screen. Create two double variables to store the 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 user clicks 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. Invoke add() to add the button to the screen. Create an instance of the LabelField class to display the resulting coordinates and invoke add() to add the field to the screen. ButtonField locButton = new ButtonField("Get location fix", ButtonField.CONSUME_CLICK); locButton.setChangeListener(new FieldChangeListener() {
55
Development Guide
Retrieving the optimal fix with GPS and geolocation
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 clear LabelField for the coordinates. Create an instance of the Thread class that invokes run(). This thread is used to process the retrieval of the location information. In run(), create a try/catch block to specify the criteria for retrieving a location. Create an instance of the BlackBerryCriteria class by invoking BlackBerryCriteria(). No arguments are passed to BlackBerryCriteria(), so the default location mode is used. Invoke enableGeolocationWithGPS(BlackBerryCriteria.FASTEST_FIX_PREFERRED) to retrieve the first available location fix. In the catch block, invoke showException(), which is described in step 10, to display the error message for an UnsupportedOperationException. private void findLocation() { this._coordLabel.setText("");
}
7.
In the first try block, create a second try/catch block to retrieve a location provider. Invoke LocationProvider.getInstance() with the BlackBerryCriteria object to retrieve a location provider. In the catch block, invoke showException(), which is described in step 10, to display the error message for a LocationException. try {
56
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();
BlackBerryLocationProvider myProvider =
Development Guide
Retrieving the optimal fix with GPS and geolocation
(BlackBerryLocationProvider)LocationProvider.getInstance(myCriteria); } catch (LocationException e) { showException(e); }
8.
In the second try block, create a third try/catch block to retrieve the location information. Invoke BlackBerryLocationProvider.getLocation() with a parameter of -1 to retrieve a location provider by using the default timeout value. Invoke getLongitude() and getLatitude() to retrieve the longitudinal and latitudinal coordinates respectively. Invoke getGPSMode() to retrieve the mode that is used to retrieve the location. Create a switch block to identify whether the mode used is GPS or geolocation. Create an instance of the StringBuffer class and append the resulting coordinates and mode to the buffer. Create a String variable and invoke toString() with the StringBuffer object to return the String value for the coordinates. Invoke showResults() to display the results on the screen, which is described in step 9. In the first catch block, invoke showException(), which is described in step 10, to display the error message for an InterruptedException. In the second catch block, invoke showException(), which is described in step 10, to display the error message for a LocationException. try {
BlackBerryLocation myLocation =(BlackBerryLocation)myProvider.getLocation(-1); _longitude = myLocation.getQualifiedCoordinates().getLongitude(); _latitude = myLocation.getQualifiedCoordinates().getLatitude(); _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) {
57
Development Guide
Retrieving the optimal fix with GPS and geolocation
showException(e); } catch (LocationException e) { showException(e); }
9.
In the showResults method, invoke invokeLater() to add this section of code to the event queue of the application. Create an instance of the Runnable class and pass it as a parameter to invokeLater(). Override run() in the definition of Runnable. Invoke setText() with the String variable to specify the resulting coordinates for LabelField. 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 of Runnable. Invoke Dialog.alert() to create an alert dialog box, and pass the error message by invoking getMessage (). private void showException(final Exception e) { Application.getApplication().invokeLater(new Runnable() { public void run() { Dialog.alert(e.getMessage()); } }); }
Code sample: Retrieving the optimal single fix The following code sample demonstrates how to create a UI application that provides the fastest available location fix, which may come from a geolocation or GPS location source. import import import import import import
58
net.rim.device.api.gps.*; net.rim.device.api.system.Application; net.rim.device.api.ui.*; net.rim.device.api.ui.container.*; net.rim.device.api.ui.component.*; javax.microedition.location.*;
Development Guide
Retrieving the optimal fix with GPS and geolocation
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()
59
Retrieving the optimal fix with GPS and geolocation
Development Guide
{
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);
}
60
} catch (InterruptedException e) { showException(e); } catch (LocationException e) { showException(e); }
Retrieving the optimal fix with GPS and geolocation
Development Guide
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 fixes The following steps demonstrate how to create a UI application that provides continuous location updates by retrieving GPS fixes when the fixes are available or within the specified timeout period. If the GPS fix is unavailable, a geolocation fix is returned instead. 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.*;
61
Retrieving the optimal fix with GPS and geolocation
Development Guide
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 a value of 1, which specifies the interval to update the location coordinates. Create a variable with the type EditField to store the location updates that displays on the screen. In main(), create an instance of the new class and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor, create an instance of the MultipleFixScreen class, which is described in step 7. Invoke setTitle() to specify the title for the 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 screen for 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);
}
3.
}
startLocationUpdate(); pushScreen(screen);
Create an updateLocationScreen method that invokes invokeLater() to add this section of code to the event queue of the application. Create an instance of the Runnable class and pass it as a parameter to invokeLater(). Override run() in the definition of Runnable. Invoke setText() to display the results on the screen. private void updateLocationScreen(final String msg) { invokeLater(new Runnable() { public void run() { _status.setText(msg); } }); }
62
Development Guide
4.
Retrieving the optimal fix with GPS and geolocation
Create the framework for the startLocationUpdate method. Create a try/catch block for specifying the criteria to 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(). Invoke enableGeolocationWithGPS() to specify retrieving a GPS fix if it's available, or retrieving a geolocation fix if the GPS fix is unavailable. In the catch block, catch an UnsupportedOperationException, which indicates the location mode 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. Invoke LocationProvider.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 of Runnable and display a message that indicates the location provider could not be retrieved. Invoke setLocationListener() by passing the interval value, timeout value, and maximum age as parameters to register a listener when a location provider is available. In the catch block, catch a LocationException, which indicates the location 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 {
63
Retrieving the optimal fix with GPS and geolocation
Development Guide
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 location updates. Create an if statement to check that the location is valid. If the location is valid, retrieve the coordinates for the longitude, 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. Invoke updateLocationScreen() 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();
}
}
7.
64
}
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 }
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
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 fixes The following code sample demonstrates how to create a UI application that provides continuous location updates by retrieving GPS fixes when the fixes are available or within the specified timeout period. If the GPS fix is unavailable, a geolocation fix is returned instead. import import import import import import
net.rim.device.api.gps.*; net.rim.device.api.system.Application; net.rim.device.api.ui.*; net.rim.device.api.ui.component.*; net.rim.device.api.ui.container.*; 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()
65
Retrieving the optimal fix with GPS and geolocation
Development Guide
{
});
}
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;
66
Development Guide
} 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); }
}
}
67
Development Guide
Requesting concurrent GPS and geolocation updates
Requesting concurrent GPS and geolocation updates You can request both GPS and geolocation updates concurrently. Requesting concurrent updates provides you with flexibility in your application to specify request parameters (for example, the frequency and timeout), and to select the most suitable location information 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 a BlackBerryLocationProvider. One thread specifies a GPS location mode, and the other thread specifies a geolocation mode. Code sample: Requesting concurrent GPS and geolocation updates //In a GPS thread try { BlackBerryLocationProvider provider = (BlackBerryLocationProvider)LocationProvider.getInstance(new BlackBerryCriteria(GPSInfo.GPS_MODE_ASSIST)); } catch (LocationException e) { showException(e); } //In a geolocation thread try { BlackBerryLocationProvider provider = (BlackBerryLocationProvider)LocationProvider.getInstance(new BlackBerryCriteria(LocationInfo.GEOLOCATION_MODE_CELL)); } catch (LocationException e) { showException(e); }
68
Development Guide
Geocoding and reverse geocoding
Geocoding and reverse geocoding
4
The net.rim.device.api.lbs.Locator API provides the geocoding methods that can allow you to request geospatial coordinates for a street address. It also provides the reverse geocoding methods that can allow you to request a street address for a geospatial coordinate. You can use the geocode() methods to request geospatial coordinates. A successful request returns an array of Landmark objects. You can use the reverseGeocode() methods to request an approximate street address, city, province/state, or country. A successful 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速 device application 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 an IllegalThreadStateException. Each request is sent to theBlackBerry速 Infrastructure. If a request is unsuccessful, a LocatorException is thrown with an error code that indicates why the request is unsuccessful. If a request is unsuccessful or 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 geocoding You can retrieve geospatial coordinates by invoking Locator.geocode(). When you invoke Locator.geocode(), you must specify a street address by using an AddressInfo object or a String object of address information. Your application must request geocoding information outside of the event dispatch thread. A successful request for geocoding information will return 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()
69
Retrieve geospatial coordinates for an address by using geocoding
Development Guide
}
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's primary 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 AddressInfo class. 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 positive northern latitude and negative western longitude of the Waterloo, Ontario region are used by the LBS Locate Server to perform the geocode search. Create a try/catch block. In this block, invoke geocode() to find the address and return the 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 geocoding import net.rim.device.api.lbs.*; import javax.microedition.location.*;
70
Retrieve an address by using reverse geocoding
Development Guide
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 geocoding You can use geospatial coordinates to retrieve an address by invoking Locator.reverseGeocode(). You must specify the coordinates for the latitude and longitude by using two int fields, or by using a Coordinates object. The values for the coordinates are passed as decimal degrees, to five decimal places, with the values multiplied by 100,000. Your application must request reverse geocoding information, such as an address, outside of the event dispatch thread. A successful request for reverse geocoding 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.
71
Retrieve an address by using reverse geocoding
Development Guide
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 the application'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 the AddressInfo class. Create two int fields, and populate the fields with the values for thelatitude and longitude with five decimal accuracy multiplied by 100,000. Create a try/catch block. In this block, invoke reverseGeocode() to find the 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();
};
6.
72
}
} catch ( LocatorException lex ) { }
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
Code sample: Retrieving an address by using geospatial coordinates and reverse geocoding
Development Guide
â&#x20AC;˘ Locator.PROVINCE_STATE: returns a value that is focused on the province or state level â&#x20AC;˘ 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 and reverse geocoding import 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 ) { }
73
Development Guide
BlackBerry Maps
BlackBerry Maps
5
You can create a BlackBerry® device application that interacts with BlackBerry® Maps. BlackBerry Maps is a map and location application that can display a map, the location of the BlackBerry device, a route from a starting location to a specific ending location, 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 device application that interacts with BlackBerry Maps.
Opening BlackBerry Maps from your application You can open BlackBerry® Maps by using the Invoke.invokeApplication() method. When you use this method, you must pass in a net.rim.blackberry.api.invoke.MapsArguments parameter to customize the map view that appears. 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 settings You can open BlackBerry® Maps to display the default map view by invoking Invoke.invokeApplication() and passing in a new MapsArguments object. 1. Import the required classes. import net.rim.blackberry.api.invoke.*;
2.
74
Create a class and a constructor to use to invoke BlackBerry Maps.
Development Guide
Open BlackBerry Maps by using information from a contact
public class invokeMaps { public invokeMaps() { } }
3.
In the constructor, invoke Invoke.invokeApplication() to open BlackBerry Maps. Pass in a new MapsArguments object. Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, new MapsArguments());
Code sample: Opening BlackBerry Maps by using the default settings import 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 contact You can open BlackBerry速 Maps to display a location on a map by using the address information from a contact in the contacts application 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 using the 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);
75
Open BlackBerry Maps by using information from a contact
Development Guide
} 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. Invoke Invoke.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 contact import 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();
76
Development Guide
Open BlackBerry Maps by using specific coordinates
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 coordinates You can open BlackBerry速 Maps to display a location on a map by providing the coordinates for the latitude and longitude of a location and by specifying the zoom and rotation values. The zoom values have a range of 0 to MapView.MAX_ZOOM. The rotation 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);
77
Development Guide
4.
Open BlackBerry Maps by using a landmark
In the constructor, create an instance of the MapsArguments class using the MapView object as an argument. Invoke Invoke.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 coordinates import 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 landmark You can open BlackBerry速 Maps to display the location of a landmark on a map by specifying an array of Landmark objects. A landmark 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 address are 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];
78
Development Guide
4.
Open BlackBerry Maps by using a landmark
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 the QualifiedCoordinates 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. Invoke Invoke.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 landmark import 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);
79
Opening BlackBerry Maps by using a location document
Development Guide
}
}
Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, ma);
Opening BlackBerry Maps by using a location document You can open BlackBerry® Maps to display map locations and routes by passing in a location document. A location document is a String object that contains XML elements with attributes that can specify the location and route information. The XML elements that you can use include <lbs>, <getRoute> and <location>.
XML element: <lbs> The opening and closing <lbs> elements wrap the location document elements.
Valid parents None
Valid children <location>, <getRoute>
Attributes Attribute
Type
Description
Supported in
id
String
This value specifies the ID of a location document.
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:
BlackBerry® Java® Development Environment 4.5.0 or later BlackBerry JDE 4.5.0 or later
• •
NONE: does not clear any information DOCS: clears location and route
information from all location documents that have a specific id attribute
80
Opening BlackBerry Maps by using a location document
Development Guide
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 <lbs <lbs <lbs <lbs <lbs <lbs <lbs <lbs
clear='WatLocation'></lbs> clear='WatLocation,OttLocation'></lbs> clear='WatRoute'></lbs> clear='WatRoute,OttRoute'></lbs> clear='NONE'></lbs> clear='DOCS'></lbs> clear='LOCATIONS'></lbs> clear='ROUTES'></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 required attributes.
Valid parents <lbs>, <getRoute>
Valid children None
Attributes Attribute
Type
Description
Supported in
address
String
This attribute specifies the street address.
categories
String
This attribute specifies the category.
BlackBerry® Java® Development Environment 4.2.1 or later BlackBerry JDE 4.2.1 or later
81
Opening BlackBerry Maps by using a location document
Development Guide
Attribute
Type
Description
Supported in
city
String
country
String
description
String
This attribute specifies the city. This attribute specifies the country. This attribute specifies the description information for a location.
BlackBerry JDE 4.2.1 or later BlackBerry JDE 4.2.1 or later BlackBerry JDE 4.2.0 or later
String
fax
String
label
String
phone
String
postalCode
String
rating
double
region
String
url
String
x or the alias, lon
integer
y or the alias, lat
integer
zoom
integer
Code sample
82
This is a required attribute. This attribute specifies the email address. This attribute specifies the fax number. This attribute specifies the label that is displayed beside a location on a map. This is a required attribute. This attribute specifies the phone number. This attribute specifies the postal code or zip code. This attribute specifies the rating information in the range of 0 to 5. This attribute specifies the province or state. This attribute specifies the URL. This attribute specifies the longitude in decimal degrees with five decimal accuracy multiplied by 100,000. This is a required attribute. This attribute specifies the latitude in decimal degrees with five decimal accuracy multiplied by 100,000. This is a required attribute. This attribute specifies the zoom level from 0 to 15.
BlackBerry JDE 4.2.1 or later BlackBerry JDE 4.2.1 or later BlackBerry JDE 4.2.0 or later
BlackBerry JDE 4.2.1 or later BlackBerry JDE 4.2.1 or later BlackBerry JDE 4.2.1 or later BlackBerry JDE 4.2.1 or later BlackBerry JDE 4.2.1 or later BlackBerry JDE 4.2.0 or later
BlackBerry JDE 4.2.0 or later
BlackBerry JDE 4.2.0 or later
Development Guide
Opening BlackBerry Maps by using a location document
<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 starting and ending locations in two <location> elements in the <getRoute> block. You can use the x and y attributes, or the aliases lon and lat, in a <location> element that you nest within the <getRoute> block.
Valid parents <lbs>
Valid children <location>
Attributes None 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 document You can use a location document to display a location on a map in BlackBerry速 Maps. You can also clear locations from a map after 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 ()
83
Opening BlackBerry Maps by using a location document
Development Guide
}
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 new MapsArguments object as parameters to open BlackBerry Maps. Pass in the ARG_LOCATION_DOCUMENT property and the String variable that represents the location document as parameters for the MapsArguments class to display the location 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 be the id of the location document that contains the location information. String document = "<lbs clear='Waterloo'></lbs>";
Clear all locations from a map.
Create a String that configures the clear attribute to be LOCATIONS. String document = "<lbs clear='LOCATIONS'></lbs>";
Clear all locations and routes from a map.
Create a String that configures the clear attribute to be ALL. 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 displaying and clearing map content into one location document.
84
Development Guide
Opening BlackBerry Maps by using a location document
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 document import 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 document You can use a location document to display a route on a map in BlackBerry速 Maps. You can also clear a route from a map after it 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>";
85
Opening BlackBerry Maps by using a location document
Development Guide
4.
In the constructor, invoke Invoke.invokeApplication() using the APP_TYPE_MAPS constant and a new MapsArguments object as parameters to open BlackBerry Maps. Pass in the ARG_LOCATION_DOCUMENT property and the String variable that represents the location document as parameters for the MapsArguments class to display the route 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 be the id of the location document that contains the route information. String document = "<lbs clear='WatRoute'></lbs>";
Clear all routes from a map.
Create a String that configures the clear attribute to be ROUTES. String document = "<lbs clear='ROUTES'></lbs>";
Clear all routes and location information from a specific location documents with an id attribute.
Create a String that configures the clear attribute to be DOCS. String document = "<lbs clear='DOCS'></ lbs>";
Clear all routes and location information from a map.
Create a String that configures the clear attribute to be ALL. 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 displaying and 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
86
Development Guide
Open BlackBerry Maps by using a local search
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 search You 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 can display 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, separated by a comma (for example, 4328915,-8032480). The coordinates must be the measurement in decimal degrees with five decimal accuracy 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 the MapsArguments.ARG_LOCAL_SEARCH and String objects to represent the search criteria. The following code sample searches for hotels in Waterloo. MapsArguments ma = new MapsArguments (MapsArguments.ARG_LOCAL_SEARCH, "hotels", "Waterloo");
87
Using KML documents with BlackBerry Maps
Development Guide
4.
In the constructor, invoke Invoke.invokeApplication() to open BlackBerry Maps. Pass in the MapsArguments object. Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, ma);
Code sample: Opening BlackBerry Maps by using a local search import 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 Maps You 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 the associated KML Reference.
Supported KML elements BlackBerry® Maps supports the following KML elements: KML element
Valid children
kml
--
Document address description name phoneNumber Style
88
Supported in
BlackBerry® Java® Development Environment4.6 or later -BlackBerry JDE 5.0 -BlackBerry JDE 5.0 -BlackBerry JDE 5.0 -BlackBerry JDE 5.0 -BlackBerry JDE 5.0 Icon, IconStyle, LineStyle, PolyStyle, color, BlackBerry JDE 5.0 href, width
Using KML documents with BlackBerry Maps
Development Guide
KML element
Valid children
Supported in
Placemark
coordinates, Point
Placemark
coordinates, innerBoundaryIs, LinearRing,
BlackBerry JDE 4.6 BlackBerry JDE 5.0
LineString, outerBoundaryIs, Point, Polygon, styleUrl
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 they must 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 ranges from -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> element to place an image, that is contained in the <Icon> element, over location on a map. The <LatLonBox> element specifies where to position the overlay on the map. You can repeat the <GroundOverlay> element block to specify new overlays and associated 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>
89
Development Guide
Using KML documents with BlackBerry Maps
<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 document You 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 the KML 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 the MapsArguments object. Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, ma);
Code sample: Invoking BlackBerry Maps by using a KML document
90
Development Guide
Opening BlackBerry Maps from the BlackBerry Browser
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 Browser You can use the BlackBerry速 Browser to open BlackBerry速 Maps and load a location document. The web server MIME type must be correctly configured. Location documents have a MIME type of "text/vnd.rim.location.xloc".
91
Development Guide
Custom maps
Custom maps
6
Adding a map to an application You can add a map to an application by using the MapField class and RichMapField class, which are provided in the net.rim.device.api.lbs.maps.ui package. For example, you can create an application that displays a map that shows the 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 following functionality 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 features to 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 is set 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 register the 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 two MapField instances running at the same time, two threads are used. The thread ends when the MapField instance is processed for garbage collection. You should make sure the application does not exceed the limit of available threads. To end the thread for the MapField or RichMapField instance, you must invoke close(), which removes the field as a listener from specific classes and allows all appropriate classes to be processed for garbage collection. Code sample: Adding a map by using the MapField class MapField map = new MapField(); add(map);
Code sample: Adding a map by using the RichMapField class
92
Development Guide
Adding a map to an application
RichMapField map = MapFactory.getInstance().generateRichMapField(); add(map);
Code sample: Responding to changes in a MapField class 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 application The following steps describe how to add a map to a BlackBerry速 device application by using the RichMapField class, and how 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.
93
Adding a map to an application
Development Guide
import import import import import
2.
net.rim.device.api.lbs.maps.*; net.rim.device.api.lbs.maps.model.*; net.rim.device.api.lbs.maps.ui.*; net.rim.device.api.ui.*; net.rim.device.api.ui.container.*;
Create the application framework by extending the UiApplication class. In main(), create an instance of the new class and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor, invoke pushScreen() to display the custom screen for the application. The MapScreen class, which is described in step 3, 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() to create 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 and then 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. Invoke setCentreAndZoom() 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);
94
Development Guide
Specifying locations on a map
Code sample: Adding a map to an application import import import import import
net.rim.device.api.lbs.maps.*; net.rim.device.api.lbs.maps.model.*; net.rim.device.api.lbs.maps.ui.*; net.rim.device.api.ui.*; 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 map You can specify a location on a map by using the MapPoint class that is provided in the net.rim.device.api.lbs.maps.model package. MapPoint represents the geographical coordinates (latitude and longitude) for a location. You can use MapPoint to focus the map view to display a specific location (for example, you can set the center location for the map). Your application can display a marker icon to identify a location on a map by using the MapLocation class. MapLocation is an extension of MapPoint. MapLocation represents the geographical coordinates (latitude and longitude), a label, and a description for the location and generates a marker icon (a red pushpin) for the location. You can use MapLocation to provide
95
Development Guide
Tagging and setting the visibility for locations on a map
a point of interest on a map for a specified latitude and longitude (for example, a city). The map displays a marker icon and a label (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 class MapLocation location = new MapLocation(43.46518, -80.52237, "Waterloo", "This is Waterloo");
Tagging and setting the visibility for locations on a map You can assign tags to locations that are stored in a MapDataModel class. Each MapField class has an associated MapDataModel instance. The MapDataModel class that is provided in the net.rim.device.api.lbs.maps.model package, represents a container. You can add locations and associated data for the locations to the container by invoking MapDataModel.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 invoke MapDataModel.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() method allows you to specify a tag for a single mappable item that is in the container. Multiple locations can have the same tag (for example, all RIM offices can be tagged "RIM"), and a single location can have multiple tags (for example, a residence can have tags 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 in MapDataModel are visible. For example, you can add the tag "park" to several locations and you can specify that only the locations with the tag "park" are displayed on the map. You can specify the items that are visible on the map by first invoking MapDataModel.setVisibleNone() to turn off the visibility for all items, and then invoking MapDataModel.setVisible() to turn on the visibility for the specified items.
96
Tagging and setting the visibility for locations on a map
Development Guide
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 map The following steps describe how to assign tags to mappable items that are stored in a MapDataModel class. The visibility is set 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 import import import import
2.
net.rim.device.api.lbs.maps.*; net.rim.device.api.lbs.maps.model.*; net.rim.device.api.lbs.maps.ui.*; net.rim.device.api.ui.*; net.rim.device.api.ui.container.*;
Create the application framework by extending the UiApplication class. In main(), create an instance of the new class and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor, invoke pushScreen() to display the custom screen for the application. The MapTagScreen, which is described in step 3, represents the custom screen.
97
Development Guide
Tagging and setting the visibility for locations on a map
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() to create 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, and then invoke generateRichMapField() to generate the map field. Invoke add() to add the RichMapField instance to 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 of each 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.
98
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 use the identifier to access the item in MapDataModel and assign another tag to a mappable item by invoking tag(), and passing as arguments the identifier and the tag. In the following code sample, two locations are added to MapDataModel, and each location is assigned two tags.
Development Guide
Tagging and setting the visibility for locations on a map
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 the appropriate 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. Invoke setVisibleNone() to turn the visibility off for all the locations. Invoke setVisible() and pass the "work" tag as an argument 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 to recalculate 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 map The following code sample creates a map, assigns tags to multiple locations, and displays only the locations that have a "work" tag. import import import import import
net.rim.device.api.ui.*; net.rim.device.api.ui.container.*; net.rim.device.api.lbs.maps.*; net.rim.device.api.lbs.maps.model.*; 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()
99
Development Guide
{ }
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" );
}
100
}
data.setVisibleNone(); data.setVisible( "work" ); map.getMapField().update( true );
Creating a static image of a map
Development Guide
Creating a static image of a map You can create a static image of a map by invoking MapField.getImage() , which is provided in the net.rim.device.api.lbs.maps.ui package, or MapFactory.generateStaticImage() , which is provided in the 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 that is visible on the map. MapField.getImage() is used to capture images in UI applications, where the map is a field on the screen. For example, in an application that displays a map of points of interest, you can provide a button that BlackBerry® device users 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 and the zoom level of the image, and calculate the coordinates based on the mappable items that are provided. Method
Description
This method uses a MappableVector class and provides the application with control over the coordinates for the center and the zoom MappableVector data) level of the map image. generateStaticMapImage This method uses a MapDataModel class and provides the application (MapDimensions mapProperties, with control over the coordinates for the center and the zoom level of the MapDataModel data) map image. generateStaticMapImage(XYDimension This method calculates the center and zoom level of the image based on imageSize, MappableVector data) the mappable data in the MappableVector. generateStaticMapImage
(MapDimensions mapProperties,
Code sample: Creating a static image of a map in a UI application // add the data to a collection MapDataModel 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 size MapField map = new MapField(data, 200, 200);
101
Development Guide
Adding fields on top of a map
// create the image Bitmap image = map.getImage();
Code sample: Creating a static image of a map (map center and zoom level are calculated) // add the data to a collection MappableVector 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 image XYDimension imageSize = new XYDimension( 200, 100 ); // create the image Bitmap 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 collection MapDataModel 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 map data.add( (Mappable) new MapLocation( 43.49487, -80.55335, "Dustin", null), null, false ); // specify the image size, center and zoom level MapDimensions dim = new MapDimensions( 200, 100 ); dim.setCentre( andrew ); dim.setZoom( 3 ); // create the image Bitmap map = MapFactory.getInstance().generateStaticMapImage( dim, data );
Adding fields on top of a map You 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 directly rendered on the map.
102
Development Guide
Displaying KML overlays on a map
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 from RichMapField to the other UI components on the screen. If you want to make RichMapField the exclusive field on the screen (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 with the other UI components. When RichMapField has focus, RichMapField actively consumes all input events, such as a user clicking the trackpad. Giving focus to RichMapField allows a user to pan and zoom the map without inadvertently exiting the map and moving to other components on the screen. When RichMapField does not have focus, RichMapField does not consume 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 map RichMapField 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 screen RichMapField richMapField = MapFactory.getInstance().generateRichMapField(); MapField map = richMapField.getMapField(); map.getAction().disableOperationMode( MapConstants.MODE_SHARED_FOCUS ); Related topics Adding a map to an application, 92
Displaying KML overlays on a map KML 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 a map field by specifying the URL of the KML document in the MapFactory.populateDataModelFromKmlUrl (MapDataModel model, String url, String tag) method.
103
Development Guide
Displaying KML overlays on a map
Your application can display KML data in a map field only if the KML document is retrieved through the BlackBerry速 Internet Service 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 overlay String officeTag = "RIM offices"; String officeUrl = "http://www.example.com/rim_offices.kml"; //create the map field RichMapField view = MapFactory.getInstance().generateRichMapField(); // retrieve the KML document and populate the data model MapDataModel model = view.getModel(); MapFactory.getInstance().populateDataModelFromKmlUrl( model, officeUrl, officeTag ); // display only the RIM offices and center the view on the visible locations model.setVisibleNone(); model.setVisible( officeTag ); view.getMapField().update( true ); Related topics Create a basic KML document, 89 Supported KML elements, 88
104
Navigation
Development Guide
Navigation
7
Retrieving the estimated travel time and distance You can request the estimated time and distance for automobile travel to destinations in the United States and Canada by using the Travel Time API, which is provided in the net.rim.device.api.lbs.travel package. For example, you can create a social 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 starting and ending locations. The Travel Time server uses current and historical traffic information to calculate the estimated time and distance for the trip. You can create a request by creating an instance of the TravelTimeEstimator class and specifying the geospatial coordinates for the starting and ending locations, and the starting time of the trip. You can use the current time or a future time for the starting time of the trip. TravelTimeEstimator is a singleton class that supports synchronous and asynchronous requests. A synchronous request blocks processes on the current thread until the request returns the travel time and distance estimate or throws an exception. An asynchronous request returns to the thread after sending a request for an estimate. The results are returned asynchronously to a caller-provided listener object. You should request the estimated travel time and distance asynchronously, so that the request does not block the current thread. TravelTimeEstimator returns the results by using an instance of the TravelTime class.
Retrieve the estimated travel time and distance You can create an application that retrieves the estimated time and distance it takes to travel between two locations. In the following steps, a UI application is created that contains a text field in which the BlackBerry速 device user types a destination address, a button that the user clicks to retrieve the estimated time and distance to reach the destination, and a field to display the results. Before you begin: Make sure the BlackBerry速 device or BlackBerry Smartphone Simulator has GPS enabled. 1.
Import the required classes and interfaces. import import import import import import import
net.rim.device.api.lbs.Locator; net.rim.device.api.lbs.travel.*; net.rim.device.api.system.*; net.rim.device.api.ui.*; net.rim.device.api.ui.component.*; net.rim.device.api.ui.container.*; javax.microedition.location.*;
105
Development Guide
2.
Retrieving the estimated travel time and distance
Create the application framework by extending the UiApplication class. In main(), create an instance of the new class and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor, invoke pushScreen() to display the custom screen for the application. The TravelTimeScreen class, described in step 3, represents the custom screen. public final class MyTravelTimeDemo extends UiApplication { public static void main(String[] args) { MyTravelTimeDemo theApp = new MyTravelTimeDemo(); theApp.enterEventDispatcher(); } public MyTravelTimeDemo() { pushScreen(new TravelTimeScreen()); } }
3.
Create the framework for the custom screen by extending the MainScreen class. class TravelTimeScreen extends MainScreen { private BasicEditField _destinationField; private LabelField _timeLabel; private LabelField _distanceLabel;
4.
In the constructor, invoke super() to create a default menu. Invoke setTitle() to specify the title for the screen. Create an instance of the BasicEditField class to create a text field for the user to type the destination in. Invoke add () to add the field to the screen. Create an instance of the ButtonField class to create a button to retrieve the travel time and distance estimate. Invoke Field.setChangeListener() to listen for changes to the button. Invoke findTravelTime(), which is described in step 5, to retrieve the travel time and distance estimate when the user clicks the button. Invoke add() to add the button to the screen. Create instances of the LabelField class to display the travel time and distance results. public TravelTimeScreen() { super(DEFAULT_CLOSE | DEFAULT_MENU); setTitle(new LabelField("Travel Time Demo" , Field.USE_ALL_WIDTH | DrawStyle.HCENTER)); this._destinationField = new BasicEditField("Destination: ", "", 500, TextField.NO_NEWLINE); add(this._destinationField); ButtonField travelButton = new ButtonField("Get Travel Estimate", ButtonField.CONSUME_CLICK); travelButton.setChangeListener(new FieldChangeListener() { public void fieldChanged(Field field, int context)
106
Retrieving the estimated travel time and distance
Development Guide
{ }
findTravelTime();
}); add(travelButton);
}
5.
this._timeLabel = new LabelField(); add(this._timeLabel); this._distanceLabel = new LabelField(); add(this._distanceLabel);
Create a method in the TravelTimeScreen class to provide the travel time estimate. Create an instance of the String class that invokes getText() to retrieve the destination that the user typed. Validate that the field is not empty by checking for a null value or for a length of 0 in the destination field. Clear the travel time and distance result fields. private void findTravelTime() { final String destination = this._destinationField.getText(); if ((destination == null) || (destination.length() == 0)) { Dialog.alert("Destination field cannot be empty"); return; } this._timeLabel.setText(""); this._distanceLabel.setText("");
6.
Retrieve the geospatial coordinates for the starting and ending locations, by first creating an instance of the Thread class in the findTravelTime method that invokes run(). In run(), in a try/catch block, invoke Locator.geocode () and pass as a parameter the destination String to find the address and return an array of Landmark objects. Invoke Landmark.getQualifiedCoordinates() to retrieve the geospatial coordinates for the destination by using the geolocation service. Invoke LocationProvider.getInstance() to retrieve a location provider to request the current location. Invoke Location.getQualifiedCoordinates() to retrieve the geospatial coordinates for the current location by using GPS. Alternatively, if GPS is unavailable, you can use the geolocation service to retrieve the coordinates for the current location. Thread travelTimeThread = new Thread() { public void run() { try { final Landmark[] landmarks = Locator.geocode(destination.replace('\n', ' '), null); Coordinates endPoint = landmarks[0].getQualifiedCoordinates(); LocationProvider provider = LocationProvider.getInstance(null); if (provider == null) {
107
Retrieving the estimated travel time and distance
Development Guide
throw new IllegalStateException("no LocationProvider available"); } Coordinates startPoint = provider.getLocation(-1).getQualifiedCoordinates();
7.
Create an instance of the TravelTimeEstimator class by invoking TraveTimeEstimator.getInstance(). Invoke requestArrivalEstimate() to request the estimated travel time and distance. Specify the Coordinates objects for the starting and ending locations, and specify the starting time. In this example, a synchrous request is made because a separate thread was created to retrieve the geospatial coordinates. You can use the TravelTime.START_NOW constant to indicate that travel starts immediately. Invoke showResults(), which is described in step 8, to display the results. TravelTimeEstimator estimator = TravelTimeEstimator.getInstance(); final TravelTime travelTime = estimator.requestArrivalEstimate(startPoint, endPoint, TravelTime.START_NOW, null); showResults(travelTime);
8.
In the showResults method, invoke invokeLater() to add this section of code to the event queue of the application. Create an instance of the Runnable class and pass it as a parameter to invokeLater(). Override run() in the definition of Runnable. Invoke getElapsedTime() to retrieve the estimated travel time. Convert the returned travel time from milliseconds to an hour: minute: seconds format. Invoke getDistance() to retrieve the estimated travel distance. Convert the returned distances from meters to kilometers. Invoke setText() to display the results for the travel time and distance. private void showResults(final TravelTime travelTime) { Application.getApplication().invokeLater(new Runnable() { public void run() { long value = travelTime.getElapsedTime() / 1000; long seconds = value % 60; value /= 60; long minutes = value % 60; long hours = value / 60; StringBuffer buffer = new StringBuffer(); buffer.append(hours); buffer.append(':'); if (minutes < 10) { buffer.append('0'); } buffer.append(minutes); buffer.append(':'); if (seconds < 10) { buffer.append('0'); }
108
Retrieving the estimated travel time and distance
Development Guide
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 import import import import import import
net.rim.device.api.lbs.Locator; net.rim.device.api.lbs.travel.*; net.rim.device.api.system.*; net.rim.device.api.ui.*; net.rim.device.api.ui.component.*; net.rim.device.api.ui.container.*; 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,
109
Retrieving the estimated travel time and distance
Development Guide
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();
available");
LocationProvider provider = LocationProvider.getInstance(null); if (provider == null) { throw new IllegalStateException("no LocationProvider
} Coordinates startPoint = provider.getLocation(-1).getQualifiedCoordinates(); TravelTimeEstimator estimator =
110
Retrieving the estimated travel time and distance
Development Guide
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);
111
Development Guide
}
112
}
});
Retrieving the estimated travel time and distance
Development Guide
Find more information • • • • •
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.
113
Development Guide
Glossary
Glossary
9
API application programming interface CDMA Code Division Multiple Access GPS Global Positioning System HTTP Hypertext Transfer Protocol IT policy An IT policy consists of various IT policy rules that control the security features and behavior of BlackBerry devices, BlackBerry enabled devices, the BlackBerry速 Desktop Software, and the BlackBerry速 Web Desktop Manager. JSR Java速 Specification Request KML Keyhole Markup Language MIME Multipurpose Internet Mail Extensions NMEA National Marine Electronics Association PDE Position Determination Entity WLAN wireless local area network XML Extensible Markup Language
114
Development Guide
Provide feedback
Provide feedback
10
To provide feedback on this deliverable, visit www.blackberry.com/docsfeedback.
115
Document revision history
Development Guide
Document revision history Date
Description
3 September 2010
Changed the following topics: • • • • • •
16 August 2010
Added the following topics: • • • • • • • • • • • • • • • • • • • •
116
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
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
11
Document revision history
Development Guide
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
117
Development Guide
Legal notice
Legal notice
12
©2010 Research In Motion Limited. All rights reserved. BlackBerry®, RIM®, Research In Motion®, SureType®, SurePress™ and related 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. OpenGIS is a trademark of Open Geospatial Consortium, Inc. Wi-Fi is a trademark of the Wi-Fi Alliance. All other trademarks are the property of their respective owners. This documentation including all documentation incorporated by reference herein such as documentation provided or made available 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 this documentation. In order to protect RIM proprietary and confidential information and/or trade secrets, this documentation may describe some aspects of RIM technology in generalized terms. RIM reserves the right to periodically change information that is 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 services including components and content such as content protected by copyright and/or third-party web sites (collectively the "Third Party 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 Services in 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, INCLUDING WITHOUT LIMITATION, ANY CONDITIONS, ENDORSEMENTS, GUARANTEES, REPRESENTATIONS OR WARRANTIES OF DURABILITY, FITNESS FOR A PARTICULAR PURPOSE OR USE, MERCHANTABILITY, MERCHANTABLE QUALITY, NONINFRINGEMENT, SATISFACTORY QUALITY, OR TITLE, OR ARISING FROM A STATUTE OR CUSTOM OR A COURSE OF DEALING OR USAGE OF TRADE, OR RELATED TO THE DOCUMENTATION OR ITS USE, OR PERFORMANCE OR NON-PERFORMANCE OF ANY SOFTWARE, HARDWARE, SERVICE, OR ANY THIRD PARTY PRODUCTS AND SERVICES REFERENCED HEREIN, ARE HEREBY EXCLUDED. YOU MAY ALSO HAVE OTHER RIGHTS THAT VARY BY STATE OR PROVINCE. SOME JURISDICTIONS MAY NOT ALLOW THE EXCLUSION OR LIMITATION OF IMPLIED WARRANTIES AND CONDITIONS. TO THE EXTENT PERMITTED BY LAW, ANY IMPLIED WARRANTIES OR CONDITIONS RELATING TO THE DOCUMENTATION TO THE EXTENT THEY CANNOT BE EXCLUDED AS SET OUT ABOVE, BUT CAN BE LIMITED, ARE HEREBY LIMITED TO NINETY (90) DAYS FROM THE 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 LIABLE FOR ANY TYPE OF DAMAGES RELATED TO THIS DOCUMENTATION OR ITS USE, OR PERFORMANCE OR NONPERFORMANCE OF ANY SOFTWARE, HARDWARE, SERVICE, OR ANY THIRD PARTY PRODUCTS AND SERVICES REFERENCED HEREIN 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,
118
Development Guide
Legal notice
FAILURE TO REALIZE ANY EXPECTED SAVINGS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, LOSS OF BUSINESS OPPORTUNITY, OR CORRUPTION OR LOSS OF DATA, FAILURES TO TRANSMIT OR RECEIVE ANY DATA, PROBLEMS ASSOCIATED 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 OF SUBSTITUTE GOODS, COSTS OF COVER, FACILITIES OR SERVICES, COST OF CAPITAL, OR OTHER SIMILAR PECUNIARY LOSSES, WHETHER OR NOT SUCH DAMAGES WERE FORESEEN OR UNFORESEEN, AND EVEN IF RIM HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW IN YOUR JURISDICTION, RIM SHALL HAVE NO OTHER OBLIGATION, DUTY, OR LIABILITY WHATSOEVER IN CONTRACT, TORT, OR OTHERWISE TO YOU INCLUDING ANY LIABILITY FOR NEGLIGENCE OR STRICT LIABILITY. THE LIMITATIONS, EXCLUSIONS, AND DISCLAIMERS HEREIN SHALL APPLY: (A) IRRESPECTIVE OF THE NATURE OF THE CAUSE 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 BREACHES OR 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 AIRTIME SERVICE PROVIDERS), AUTHORIZED RIM DISTRIBUTORS (ALSO INCLUDING AIRTIME SERVICE PROVIDERS) AND THEIR RESPECTIVE 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 LIABILITY ARISING 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 your airtime service provider has agreed to support all of their features. Some airtime service providers might not offer Internet browsing functionality with a subscription to the BlackBerry速 Internet Service. Check with your service provider for availability, roaming arrangements, service plans and features. Installation or use of Third Party Products and Services with RIM's products and services may require one or more patent, trademark, copyright, or other licenses in order to avoid infringement or violation of third party rights. You are solely responsible for determining whether to use Third Party Products and Services and if any third party licenses are required to do so. If required you are responsible for acquiring them. You should not install or use Third Party Products and Services until all necessary licenses have been acquired. Any Third Party Products and Services that are provided with RIM's products 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 relation thereto. Your use of Third Party Products and Services shall be governed by and subject to you agreeing to the terms of separate licenses and other agreements applicable thereto with third parties, except to the extent expressly covered by a license or other agreement with RIM. Certain features outlined in this documentation require a minimum version of BlackBerry速 Enterprise Server, BlackBerry速 Desktop Software, 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 WARRANTIES PROVIDED BY RIM FOR PORTIONS OF ANY RIM PRODUCT OR SERVICE OTHER THAN THIS DOCUMENTATION. Research In Motion Limited 295 Phillip Street
119
Development Guide
Waterloo, ON N2L 3W8 Canada Research In Motion UK Limited Centrum House 36 Station Road Egham, Surrey TW20 9LF United Kingdom Published in Canada
120
Legal notice