Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Version: 5.0
Development Guide
Contents
1 GPS overview................................................................................................................................................................................ 4 6 6 6 7 8 8 9 11 11 11 11 13 15 15 17 18 19 21 22 22 23 24 26 27 27 30 30 34 35 37 2 Specifying the GPS mode........................................................................................................................................................... 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..................................................................................... GPS Modes.............................................................................................................................................................................. 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....................................................................................................... 3 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.......................................................................... 4 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................................................................................................ Retrieving location information by using the BlackBerryLocation class.................................................................................. Retrieve satellite information by using the BlackBerryLocation class............................................................................. 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)...................................................................................................................... 5 Geocoding and reverse geocoding........................................................................................................................................... Retrieve geospatial coordindates for an address by using geocoding..................................................................................... Retrieve an address by using reverse geocoding........................................................................................................................ 6 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.............................................................................. 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........................................................................................................... Retrieving a GPS location by using a web page.......................................................................................................................... Retrieve a GPS location by using a web page............................................................................................................................. Embedding a map in an application............................................................................................................................................. Embed a map in an application............................................................................................................................................ 7 Glossary......................................................................................................................................................................................... 8 Provide feedback......................................................................................................................................................................... 9 Document revision history.........................................................................................................................................................
37 38 41 41 43 46 46 46 47 49 50 52 52 53 55 55 57 59 60 60 61 61 62 63 63 65 66 67 73 74 75
10 Legal notice..................................................................................................................................................................................
77
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
GPS overview
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
You must specify the GPS mode to retrieve the location of a BlackBerry device. GPS modes include autonomous, assisted and cell site. Autonomous mode relies on GPS satellites only. Assisted mode relies on GPS satellites and servers on the wireless network. Cell site mode relies on the geolocation service, or the wireless network to provide the location information of the current base station.
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);
Development Guide
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;
GPS mode Autonomous Autonomous Assisted or data optimal Assisted or speed optimal Assisted or MSBased Assisted or accuracy optimal Assisted or MSAssisted Cell site
Response time Fix frequency any any any quality of service quality of service quality of service quality of service any single or multiple single or multiple single or multiple multiple multiple single
yes yes
single any
Development Guide
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. 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.
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.
Development Guide
Description 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. 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.
assisted MS-based
accuracy optimal
data optimal
Development Guide
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.
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);
10
Development Guide
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 } } }
2.
11
Development Guide
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);
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);
12
Development Guide
try {
BlackBerryLocationProvider myProvider = (BlackBerryLocationProvider) LocationProvider.getInstance(myCriteria); String user = "UserID"; String pass = "Password"; String ip = "127.0.0.1"; int port = 0;
13
Development Guide
14
Development Guide
After you specify the GPS mode, you must retrieve the location provider that your application uses to support the GPS mode. A location provider represents the source of the location information and it works based on given criteria (for example, the horizontal accuracy and the power usage) . 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
15
Development Guide
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;
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);
16
Development Guide
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;
} try {
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()
17
Development Guide
1.
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);
18
Development Guide
5.
Outside of the try/catch block, invoke pauseLocationTracking(), resumeLocationTracking(), or stopLocationTracking() to pause, resume, or stop location tracking.
myProvider.pauseLocationTracking(30); myProvider.resumeLocationTracking(); myProvider.stopLocationTracking();
6.
In the class, implement the LocationListener interface. Implement the basic framework for the locationUpdated () method, and the providerStateChanged() method.
public static class handleGPSListener implements LocationListener { public void locationUpdated(LocationProvider provider, Location location) { if (location.isValid()) {} else {} } public void providerStateChanged(LocationProvider provider, int newState) { if (newState == LocationProvider.AVAILABLE) {} else if (newState == LocationProvider.OUT_OF_SERVICE) {} else if (newState == LocationProvider.TEMPORARILY_UNAVAILABLE ) {} }
19
Development Guide
try {
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 }
20
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 {
21
Development Guide
You can retrieve the location of a BlackBerry device by specifying a single GPS fix, or by specifying a location listener to retrieve continuous GPS fixes.
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);
22
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 {
23
Development Guide
2.
24
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 ) {} }
25
Development Guide
Code sample: Retrieving the GPS location of a BlackBerry device by using continuous fix requests
import javax.microedition.location.*; public class handleGPS { public handleGPS() { Criteria myCriteria = new Criteria(); try {
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 }
26
Development Guide
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.
27
Development Guide
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.
Criteria myCriteria = new Criteria(); myCriteria.setCostAllowed(false);
7.
In run(), create a try/catch block. In this block create an instance of the LocationProvider class by getting an instance of the Criteria object. Create a try/catch block within this block, and create an instance of the Location class to retrieve the current GPS fix including a 300 second timeout expiry. Populate the fields, and specify the number of satellites by invoking getExtraInfo("application/X-jsr179-location-nmea").
try { LocationProvider myLocationProvider = LocationProvider.getInstance(myCriteria); try { Location myLocation = myLocationProvider.getLocation(300); latitude = myLocation.getQualifiedCoordinates().getLatitude(); longitude = myLocation.getQualifiedCoordinates().getLongitude(); velocity = myLocation.getSpeed(); heading = myLocation.getCourse(); timeStamp = myLocation.getTimestamp(); nmeaString = myLocation.getExtraInfo ("application/X-jsr179-location-nmea");
28
Development Guide
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; public handleGPS() { gpsThread = new GPSThread(); gpsThread.start(); } private static class GPSThread extends Thread { public void run() { Criteria myCriteria = new Criteria(); myCriteria.setCostAllowed(false); 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");
29
Development Guide
return;
2.
3.
In the class, declare static fields for a thread and for each item of location information that you retrieve.
30
Development Guide
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() { } }
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 = ":";
31
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'); }
32
Development Guide
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
2.
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
34
Development Guide
{ }
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); }
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) {}
35
Development Guide
public static void main(String[] args) { } public handleGPS(int gpsMode) { if (locationProvider != null) { locationProvider.reset(); locationProvider.setLocationListener(null, -1, -1, -1); } Criteria myCriteria = new Criteria(); myCriteria.setPreferredResponseTime(Criteria.NO_REQUIREMENT); myCriteria.setCostAllowed(true); 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();
36
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.
37
Development Guide
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);
38
Development Guide
{ }
return;
5.
In the class, create a static class that implements LocationListener. Implement locationUpdated() and
providerStateChanged(). 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;
39
Development Guide
BlackBerryLocationProvider myProvider = (BlackBerryLocationProvider) LocationProvider.getInstance(myCriteria); myProvider.setLocationListener (new myLocationListener(), -1, -1, -1);
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;
40
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.
41
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 {
};
42
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 {
};
43
Development Guide
2.
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 a Thread that invokes a public run() method. In run(), create an instance of the AddressInfo class. Create two int fields, and populate each field with the latitude and longitude values 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.
Pass one of the following parameters to Locator.reverseGeocode(): Locator.ADDRESS: requests the nearest address or nearest street to the specified latitude/longitude Locator.CITY: returns a value that is focused on the city level
44
Development Guide
Locator.COUNTRY: returns a value that is focused on the country level Locator.PROVINCE_STATE: returns a value that is focused on the province or state level Code sample: Retrieving an address by using 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();
};
45
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.
46
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);
47
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);
48
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);
49
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];
50
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);
51
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
52
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
53
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
54
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.
55
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.
56
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>";
57
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>";
58
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");
59
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
60
Development Guide
KML element
Placemark Placemark
Valid children
coordinates, Point coordinates, innerBoundaryIs, LinearRing, LineString, outerBoundaryIs, Point, Polygon, styleUrl
61
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);
62
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); } }
The following items are limitations when using KML documents with BlackBerry Maps : Unsupported KML elements are not displayed. A KML file that is locally available on the BlackBerry device cannot be displayed by BlackBerry Maps. The KML file must be on a web server that the BlackBerry device can access. A KML file which arrives on the BlackBerry device as an email attachment cannot be displayed by BlackBerry Maps. The download size limit of KML documents is typically set to 256 KB for BlackBerry devices that are associated with a BlackBerry Enterprise Server, and 512 KB for BlackBerry devices that are associated with the BlackBerry Internet Service.
Description This property returns true when GPS is supported by the BlackBerry device.
63
Development Guide
JavaScript property
blackberry .location .latitude
Description 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 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
64
Development Guide
JavaScript method
Description 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.
65
Development Guide
} 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 { }
Description Moves the position of the map by a certain number of pixels. Moves the position of the the map to the location specified by a Coordinate object. Moves the postion of the map to the specified coordinates for latitude and longitude. Rotates the current map view. Changes the zoom level of the current map view.
In the moveTo method, you can use world coordinates for the latitudinal and longitudinal coordinates. Valid ranges for latitude are -9000000 to +9000000, and ranges for longitude are -18000000 to +18000000. Some methods in the MapField class throw an IllegalArgumentException if the passed or calculated coordinates are out of range.
66
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. The myScreen class represents the custom screen, which is described in step 3.
public class MapFieldDemo extends UiApplication { public static void main(String[] args) { MapFieldDemo theApp = new MapFieldDemo(); theApp.enterEventDispatcher(); } MapFieldDemo() { pushScreen(new myScreen()); }
3.
Create the framework for the screen by extending the FullScreen class. Implement the FieldChangeLister interface to listen for events from the ButtonField object which is described in step 5. In the constructor, invoke super () to create a default menu. Invoke createUI() to create the UI, which is described in step 4.
class myScreen extends FullScreen implements FieldChangeListener { private MapField _mapField; private ButtonField _zoomIn; private ButtonField _zoomOut; private ButtonField _moveTo; private BasicEditField _moveByText; private BasicEditField _testsOutput; private ObjectChoiceField _moveUnits; private int _prevLat = 4328915; private int _prevLon = -8032480; private int _prevZoom = 4; myScreen() { super(DEFAULT_MENU | DEFAULT_CLOSE);
67
Development Guide
createUI();
4.
In the myScreen class, create a method that you can use to create the UI within a synchronized block. Create an instance of the VerticalFieldManager class to lay out the fields on the screen in a single column. Create an instance of the MapField class to create a map in BlackBerry Maps. Invoke add() to add the MapField to the VerticalFieldManager.
private void createUI() { VerticalFieldManager vfm; synchronized (Application.getEventLock()) { vfm = new VerticalFieldManager (Manager.USE_ALL_WIDTH | Manager.USE_ALL_HEIGHT); _mapField = new MapField(); _mapField.setPreferredSize(_mapField.getPreferredWidth(), (int) (Display.getHeight() * 0.66)); vfm.add(_mapField); }
5.
In createUI, create UI components so that the user can interact with the map. For each UI component, invoke Field.setChangeListener() to specify the listeners for the UI components. Invoke add() to add the UI components to the screen.
FlowFieldManager ffm = new FlowFieldManager(); ffm.add(_zoomIn = new ButtonField("Zoom In")); _zoomIn.setChangeListener(this); ffm.add(_zoomOut = new ButtonField("Zoom Out")); _zoomOut.setChangeListener(this); ffm.add(_moveUnits = new ObjectChoiceField("Units: ", new String[] { "pixels", "degrees" })); ffm.add(_moveByText = new BasicEditField("Move horizontal, vertical: ", "", 20, BasicEditField.NO_NEWLINE)); ffm.add(_moveTo = new ButtonField("Move")); _moveTo.setChangeListener(this); vfm.add(ffm); add(vfm);
6.
Set the default coordinates and the default zoom settings for the embedded map by invoking MapField.moveTo() and MapField.setZoom().
68
Development Guide
7.
In the myScreen class, implement FieldChangeListener.fieldChanged() to handle the user's interactions with the UI components on the screen.
public void fieldChanged(Field field, int context) { if (field == _zoomIn) { _mapField.setZoom(Math.max(_mapField.getZoom() - 1, _mapField.getMinZoom())); } else if (field == _zoomOut) { _mapField.setZoom(Math.min(_mapField.getZoom() + 1, _mapField.getMaxZoom())); } else if (field == _moveTo) { String amount = _moveByText.getText(); int ix = amount.indexOf(","); int horizontalDelta = 0; int verticalDelta = 0; if (ix == -1) { ix = amount.indexOf(" "); } try {
if (_moveUnits.getSelectedIndex() == 0) { _mapField.move(horizontalDelta, verticalDelta); } else { horizontalDelta += _mapField.getLongitude(); verticalDelta += _mapField.getLatitude(); _mapField.moveTo(verticalDelta, horizontalDelta);
69
Development Guide
public class MapFieldDemo extends UiApplication { public static void main(String[] args) { MapFieldDemo theApp = new MapFieldDemo(); theApp.enterEventDispatcher(); } MapFieldDemo() { pushScreen(new myScreen()); }
class myScreen extends FullScreen implements FieldChangeListener { private MapField _mapField; private ButtonField _zoomIn; private ButtonField _zoomOut; private ButtonField _moveTo; private BasicEditField _moveByText; private BasicEditField _testsOutput; private ObjectChoiceField _moveUnits; private int _prevLat = 4328915; private int _prevLon = -8032480; private int _prevZoom = 4; myScreen() { super(DEFAULT_MENU | DEFAULT_CLOSE); createUI(); } private void createUI() { VerticalFieldManager vfm; synchronized (Application.getEventLock()) { vfm = new VerticalFieldManager
70
Development Guide
FlowFieldManager ffm = new FlowFieldManager(); ffm.add(_zoomIn = new ButtonField("Zoom In")); _zoomIn.setChangeListener(this); ffm.add(_zoomOut = new ButtonField("Zoom Out")); _zoomOut.setChangeListener(this); ffm.add(_moveUnits = new ObjectChoiceField("Units: ", new String[] { "pixels", "degrees" })); ffm.add(_moveByText = new BasicEditField("Move horizontal, vertical: ", "", 20, BasicEditField.NO_NEWLINE)); ffm.add(_moveTo = new ButtonField("Move")); _moveTo.setChangeListener(this); vfm.add(ffm); add(vfm); _mapField.moveTo(_prevLat, _prevLon); _mapField.setZoom(_prevZoom);
public void fieldChanged(Field field, int context) { if (field == _zoomIn) { _mapField.setZoom(Math.max(_mapField.getZoom() - 1, _mapField.getMinZoom())); } else if (field == _zoomOut) { _mapField.setZoom(Math.min(_mapField.getZoom() + 1, _mapField.getMaxZoom())); } else if (field == _moveTo) { String amount = _moveByText.getText(); int ix = amount.indexOf(","); int horizontalDelta = 0; int verticalDelta = 0; if (ix == -1) {
71
Development Guide
} try {
ix = amount.indexOf(" ");
if (_moveUnits.getSelectedIndex() == 0) { _mapField.move(horizontalDelta, verticalDelta); } else { horizontalDelta += _mapField.getLongitude(); verticalDelta += _mapField.getLatitude(); _mapField.moveTo(verticalDelta, horizontalDelta); }
72
Development Guide
Glossary
Glossary
API application programming interface CDMA Code Division Multiple Access GPS Global Positioning System HTTP Hypertext Transfer Protocol JSR Java Specification Request KML Keyhole Markup Language MIME Multipurpose Internet Mail Extensions NMEA National Marine Electronics Association PDE Position Determination Entity XML Extensible Markup Language
73
Development Guide
Provide feedback
Provide feedback
To provide feedback on this deliverable, visit www.blackberry.com/docsfeedback.
74
Development Guide
Deleted the following topics: 15 October 2009 About the BlackBerryCriteria class Advantages of using the BlackBerryCriteria Advantages of using a BlackBerryLocationProvider
Added the following topics: 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 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
75
Development Guide
Date
Description Retrieving a GPS location by using a web page Retrieve a GPS location by using a web page Embedding a map in an application Embed a map in an application
76
Development Guide
Legal notice
Legal notice
10
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 Sun Microsystems, 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,
77
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
78
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
79