Version: 6.0
Development Guide
Contents
1 Location-based services overview............................................................................................................................................. 4 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 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.....................................................
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................................................................................................................. 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.............................................................................................................. 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............................................ 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..............................................................................
35 37 39 39 40 42 44 46 46 47 47 51 54 54 58 61 65 68 69 69 71 73 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........................................................................................................... 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............................................................................................................................................... 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.................................................................................... 8 Find more information................................................................................................................................................................ 9 Glossary......................................................................................................................................................................................... 10 Provide feedback......................................................................................................................................................................... 11 Document revision history......................................................................................................................................................... 12 Legal notice..................................................................................................................................................................................
85 87 88 88 89 89 90 91 92 92 93 95 95 96 97 99 101 102 103 105 105 105 109 113 114 115 116 118
Development Guide
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.
Development Guide
GPS overview
GPS overview
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: Making a GPS request that is based on the frequency of the GPS fix
/* * Single GPS fix */ /* JSR 179 */
Development Guide
Location myLoc = myProvider.getLocation(); /* JSR 179 extension */ BlackBerryLocation myBlackBerryLoc = myBlackBerryProvider.getLocation(); /* * Continuous GPS fixes */ /* JSR 179 */ myProvider.setLocationListener(); /* JSR 179 extension */ myBlackBerryProvider.setLocationListener();
Development Guide
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
getSupportedLocationSources() isLocationSourceSupported(int mode) getAvailableLocationSources()
Description 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.
isLocationSourceAvailable(int mode)
Development Guide
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 cell site Description 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
Development Guide
Description 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.
accuracy optimal
data optimal
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;
Response time Fix frequency any any any single or multiple single or multiple single or multiple
10
Development Guide
GPS mode Assisted or speed optimal Assisted or MSBased Assisted or accuracy optimal Assisted or MSAssisted Cell site
Response time Fix frequency quality of service quality of service quality of service quality of service any multiple multiple single
yes yes
single any
Description 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.
11
Development Guide
Method
setSatelliteInfoRequired (boolean, boolean)
Description 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.
3.
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.
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.
12
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);
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
2.
3.
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
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 {
15
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 {
16
Development Guide
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 Bluetoothenabled 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.
3. 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
Development Guide
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);
18
Development Guide
} try {
myCriteria.setCostAllowed(false); break;
Description 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.
resumeLocationTracking() stopLocationTracking()
1.
19
Development Guide
2.
3.
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);
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);
5.
Outside of the try/catch block, invoke pauseLocationTracking(), resumeLocationTracking(), or stopLocationTracking() to pause, resume, or stop location tracking.
20
Development Guide
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 ) {} }
21
Development Guide
public static class handleGPSListener implements LocationListener { public void locationUpdated(LocationProvider provider, Location location) { if (location.isValid()) { // do something } else { // invalid location } } public void providerStateChanged(LocationProvider provider, int newState) { if (newState == LocationProvider.AVAILABLE) { // available } else if (newState == LocationProvider.OUT_OF_SERVICE) { // GPS unavailable due to IT policy specification } else if (newState == LocationProvider.TEMPORARILY_UNAVAILABLE ) { // no GPS fix } }
22
Development Guide
2.
3.
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 {
23
Development Guide
3.
4.
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
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 {
25
Development Guide
2.
26
Development Guide
3.
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 {
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
Development Guide
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 } }
28
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
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 GPSThread gpsThread; double latitude; double longitude; float heading; float velocity; long timeStamp; String nmeaString;
4.
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
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");
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
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 {
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
Development Guide
2.
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 GPSThread gpsThread; int satCount; int signalQuality; int dataSource; int gpsMode;
4.
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
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.
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'); }
33
Development Guide
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
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'); }
2.
35
Development Guide
{ }
3.
In the class, define static fields for the location provider, latitude, longitude, altitude, speed and course.
static LocationProvider locationProvider; static double lat, lon; static float alt, spd, crs;
4.
In the constructor, add a code block to set up a LocationProvider instance to switch to a different method of 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
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) {}
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); }
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) { }
38
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.
2.
3.
39
Development Guide
Error handling
2.
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);
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);
5.
In the class, create a static class that implements LocationListener. Implement locationUpdated() and
providerStateChanged().
40
Development Guide
Error handling
private static class myLocationListener implements LocationListener { public void locationUpdated(LocationProvider provider, Location location) { } public void providerStateChanged(LocationProvider provider, int newState) { }
6.
In locationUpdated(), verify if the location parameter is an instance of BlackBerryLocation. If so, 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;
41
Development Guide
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;
42
Development Guide
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 { }
43
Development Guide
Description 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.
JavaScript method
blackberry .location .setAidMode (mode)
Description This method specifies which GPS mode the BlackBerry device will use to determine the GPS location. The mode can be any one of the following values: 0 for Cell Site mode 1 for Assisted mode 2 for Autonomous mode
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
44
Development Guide
JavaScript method
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. 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
Development Guide
Geolocation overview
Geolocation overview
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
GEOLOCATION_MODE GEOLOCATION_MODE_CELL GEOLOCATION_MODE_WLAN
Description 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.
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
47
Development Guide
2.
Create the application framework by extending the UiApplication class. In main(), create an instance of the new class and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor, invoke pushScreen() to display the custom screen for the application. The GeolocationScreen class, which is described in step 3, represents the custom screen.
public final class GeolocationDemo extends UiApplication { public static void main(String[] args) { GeolocationDemo theApp = new GeolocationDemo(); theApp.enterEventDispatcher(); } public GeolocationDemo() { pushScreen(new GeolocationScreen()); }
3.
Create the framework for the custom screen by extending the MainScreen class. Create an instance of the LabelField class to store the coordinates that display on the screen. Create two double variables to store the latitude and longitude values.
class GeolocationScreen extends MainScreen { private LabelField _coordLabel; private double _latitude; private double _longitude; }
4.
In the screen constructor, invoke super() to create a default menu. Invoke setTitle() to specify the title for the screen.
public GeolocationScreen() { super(DEFAULT_CLOSE | DEFAULT_MENU); setTitle(new LabelField("Geolocation Demo", Field.USE_ALL_WIDTH | DrawStyle.HCENTER)); }
5.
In the screen constructor, create an instance of the ButtonField class to create a button that the BlackBerry device user clicks to retrieve the geolocation of the device. Invoke Field.setChangeListener() to listen for changes to the button. Invoke findGeolocation(), which is described in step 6, to retrieve the geolocation when the user clicks the button. Invoke add() to add the button to the screen. Create an instance of the LabelField class to display the resulting coordinates and invoke add() to add the field to the screen.
48
Development Guide
ButtonField geolocButton = new ButtonField("Get geolocation", ButtonField.CONSUME_CLICK); geolocButton.setChangeListener(new FieldChangeListener() { public void fieldChanged(Field field, int context) { findGeolocation(); } }); add(geolocButton); this._coordLabel = new LabelField(); add(this._coordLabel);
6.
Create the framework for the findGeolocation method. Invoke setText() with an empty String value to clear LabelField for the coordinates. Create an instance of the Thread class that invokes run(). This thread is used to process the retrieval of the geolocation information. In run(), create a try/catch block to specify the geolocation mode. Create an instance of the BlackBerryCriteria class by invoking BlackBerryCriteria() and pass LocationInfo.GEOLOCATION_MODE as the mode to retrieve geolocation information. In the catch block, invoke showException(), which is described in step 10, to display the error message for an UnsupportedOperationException.
private void findGeolocation() { this._coordLabel.setText(""); Thread geolocThread = new Thread() { public void run() { try { BlackBerryCriteria myCriteria = new BlackBerryCriteria(LocationInfo.GEOLOCATION_MODE); } catch (UnsupportedOperationException e) { showException(e); } } }; geolocThread.start();
7.
In the first try block, create a second try/catch block to retrieve a location provider. Invoke LocationProvider.getInstance() with the BlackBerryCriteria object to retrieve a location provider. In the catch block, invoke showException(), which is described in step 10, to display the error message for a LocationException.
49
Development Guide
try {
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);
9.
In the showResults method, invoke invokeLater() to add this section of code to the event queue of the application. Create an instance of the Runnable class and pass it as a parameter to invokeLater(). Override run() in the definition of Runnable. Invoke setText() with the String variable to specify the resulting coordinates for the LabelField.
50
Development Guide
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
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
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);
} }; 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
Development Guide
{ }); }
Dialog.alert(e.getMessage());
Description 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.
54
Development Guide
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 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(); } public SingleFixDemo() { pushScreen(new SingleFixScreen()); }
3.
Create the framework for the custom screen by extending the MainScreen class. Create an instance of the LabelField class to store the coordinates that 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
}); add(locButton);
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(""); Thread locThread = new Thread() { public void run() { try { BlackBerryCriteria myCriteria = new BlackBerryCriteria(); myCriteria.enableGeolocationWithGPS(BlackBerryCriteria .FASTEST_FIX_PREFERRED); } catch (UnsupportedOperationException e) { showException(e); } } }; locThread.start();
7.
In the first try block, create a second try/catch block to retrieve a location provider. Invoke LocationProvider.getInstance() with the BlackBerryCriteria object to retrieve a location provider. In the catch block, invoke showException(), which is described in step 10, to display the error message for a LocationException.
try { BlackBerryLocationProvider myProvider =
56
Development Guide
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
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()); } }); }
58
Development Guide
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
Development Guide
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);
try {
60
Development Guide
} }; 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()); } }); }
61
Development Guide
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); startLocationUpdate(); pushScreen(screen);
3.
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.
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
Development Guide
1);
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(); 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());
7.
Create the framework for the custom screen by extending the MainScreen class. In the screen constructor, invoke super () to create a default menu. Create an instance of the RichTextField to display an instructional message. Invoke add () to add the RichTextField to the screen.
64
Development Guide
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); }
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);
65
Development Guide
});
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); }
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());
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
68
Development Guide
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.
2.
69
Development Guide
{ }
3. 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 {
};
70
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 {
};
2.
71
Development Guide
3. 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.
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
72
Development Guide
Code sample: Retrieving an address by using geospatial coordinates and reverse geocoding
Locator.PROVINCE_STATE: returns a value that is focused on the province or state level Locator.POSTAL_CODE: returns a value that is focused on the postal code or zip code level
Code sample: Retrieving an address by using geospatial coordinates 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();
};
73
Development Guide
BlackBerry Maps
BlackBerry Maps
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.
2.
74
Development Guide
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());
2.
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
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);
76
Development Guide
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);
2.
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.
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);
2.
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.
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);
79
Development Guide
Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, ma);
Valid parents
None
Valid children
<location>, <getRoute>
Attributes
Attribute
id
Type
String
Description This value specifies the ID of a location document. This value specifies the clearing action to perform on the information in a map. The value is a list of location document IDs separated by commas, or one of the following values:
NONE: does not clear any information DOCS: clears location and route
Supported in BlackBerry Java Development Environment 4.5.0 or later BlackBerry JDE 4.5.0 or later
clear
String
80
Development Guide
Attribute
Type
Description
LOCATIONS: clears all the location
Supported in
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>
Valid parents
<lbs>, <getRoute>
Valid children
None
Attributes
Attribute
address categories
Type
String String
Description This attribute specifies the street address. This attribute specifies the category.
Supported in BlackBerry Java Development Environment 4.2.1 or later BlackBerry JDE 4.2.1 or later
81
Development Guide
Attribute
city country description
Type
String String String
Description This attribute specifies the city. This attribute specifies the country. This attribute specifies the description information for a location. 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.
Supported in 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.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
integer
zoom
integer
Code sample
82
Development Guide
<lbs id='Waterloo'> <location x='-8052237' y='4346518' label='Waterloo, ON' description='Waterloo' zoom='10' /> </lbs>
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>
2.
83
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 Clear a location from a map. Steps 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>";
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
String document = "<lbs clear='Waterloo' id='NewZone'> <location x='-8050000' y='4340000' label='NewZone' description='NewZone' zoom='10' /> </lbs>";
2.
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
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 Clear a route from a map. Steps 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 and location information from a specific location documents with an id attribute.
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>";
86
Development Guide
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)); } }
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
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);
Valid children --
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
88
Development Guide
KML element
Placemark Placemark
Valid children
coordinates, Point coordinates, innerBoundaryIs, LinearRing, LineString, outerBoundaryIs, Point, Polygon, styleUrl
89
Development Guide
<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>
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);
90
Development Guide
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); } }
91
Development Guide
Custom maps
Custom maps
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);
92
Development Guide
1.
93
Development Guide
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 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
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); } }
95
Development Guide
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.
96
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" );
1.
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 MapTagScreen, which is described in step 3, represents the custom screen.
97
Development Guide
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. 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.
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.
98
Development Guide
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" ); data.setVisibleNone(); data.setVisible( "work" ); map.getMapField().update( true );
100
Development Guide
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. 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
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 );
102
Development Guide
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
103
Development Guide
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
Development Guide
Navigation
Navigation
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.
105
Development Guide
2.
Create the application framework by extending the UiApplication class. In main(), create an instance of the new class and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor, invoke pushScreen() to display the custom screen for the application. The TravelTimeScreen class, described in step 3, represents the custom screen.
public final class MyTravelTimeDemo extends UiApplication { public static void main(String[] args) { MyTravelTimeDemo theApp = new MyTravelTimeDemo(); theApp.enterEventDispatcher(); } public MyTravelTimeDemo() { pushScreen(new TravelTimeScreen()); } }
3.
Create the framework for the custom screen by extending the MainScreen class.
class TravelTimeScreen extends MainScreen { private BasicEditField _destinationField; private LabelField _timeLabel; private LabelField _distanceLabel;
4.
In the constructor, invoke super() to create a default menu. Invoke setTitle() to specify the title for the screen. Create an instance of the BasicEditField class to create a text field for the user to type the destination in. Invoke add () to add the field to the screen. Create an instance of the ButtonField class to create a button to retrieve the travel time and distance estimate. Invoke Field.setChangeListener() to listen for changes to the button. Invoke findTravelTime(), which is described in step 5, to retrieve the travel time and distance estimate when the user clicks the button. Invoke add() to add the button to the screen. Create instances of the LabelField class to display the travel time and distance results.
public TravelTimeScreen() { super(DEFAULT_CLOSE | DEFAULT_MENU); setTitle(new LabelField("Travel Time Demo" , Field.USE_ALL_WIDTH | DrawStyle.HCENTER)); this._destinationField = new BasicEditField("Destination: ", "", 500, TextField.NO_NEWLINE); add(this._destinationField); ButtonField travelButton = new ButtonField("Get Travel Estimate", ButtonField.CONSUME_CLICK); travelButton.setChangeListener(new FieldChangeListener() { public void fieldChanged(Field field, int context)
106
Development Guide
{ }
findTravelTime();
}); add(travelButton); this._timeLabel = new LabelField(); add(this._timeLabel); this._distanceLabel = new LabelField(); add(this._distanceLabel);
5.
Create a method in the TravelTimeScreen class to provide the travel time estimate. Create an instance of the String class that invokes getText() to retrieve the destination that the user typed. Validate that the field is not empty by checking for a null value or for a length of 0 in the destination field. Clear the travel time and distance result fields.
private void findTravelTime() { final String destination = this._destinationField.getText(); if ((destination == null) || (destination.length() == 0)) { Dialog.alert("Destination field cannot be empty"); return; } this._timeLabel.setText(""); this._distanceLabel.setText("");
6.
Retrieve the geospatial coordinates for the starting and ending locations, by first creating an instance of the Thread class in the findTravelTime method that invokes run(). In run(), in a try/catch block, invoke Locator.geocode () and pass as a parameter the destination String to find the address and return an array of Landmark objects. Invoke Landmark.getQualifiedCoordinates() to retrieve the geospatial coordinates for the destination by using the geolocation service. Invoke LocationProvider.getInstance() to retrieve a location provider to request the current location. Invoke Location.getQualifiedCoordinates() to retrieve the geospatial coordinates for the current location by using GPS. Alternatively, if GPS is unavailable, you can use the geolocation service to retrieve the coordinates for the current location.
Thread travelTimeThread = new Thread() { public void run() { try { final Landmark[] landmarks = Locator.geocode(destination.replace('\n', ' '), null); Coordinates endPoint = landmarks[0].getQualifiedCoordinates(); LocationProvider provider = LocationProvider.getInstance(null); if (provider == null) {
107
Development Guide
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
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);
});
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
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(); LocationProvider provider = LocationProvider.getInstance(null); if (provider == null) { throw new IllegalStateException("no LocationProvider
available");
110
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
Development Guide
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
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
To provide feedback on this deliverable, visit www.blackberry.com/docsfeedback.
10
115
Development Guide
11
Added the following topics: Add a map to an application Adding a map to an application Adding fields on top of a map Creating a static image of a map Displaying KML overlays on a map Geolocation overview Geolocation modes Location-based services overview Querying location sources Requesting concurrent GPS and geolocation updates Retrieve the location of a device by using the geolocation service Retrieve the estimated travel time and distance Retrieve optimal multiple fixes Retrieve the optimal single fix Retrieving the location of a device by using the geolocation service Retrieving the estimated travel time and distance Retrieving the optimal fix with GPS and geolocation Specifying locations on a map Tag and set the visibility for locations on a map Tagging and setting the visibility for locations on a map
116
Development Guide
Date
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
Legal notice
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