Current latitude and longitude in a BlackBerry app - blackberry

I want to get the user's latitude and longitude in my BlackBerry app, and then generate the maps according to it.
How can I do that?
my code is:
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.location.Criteria;
import javax.microedition.location.Location;
import javax.microedition.location.LocationListener;
import javax.microedition.location.LocationProvider;
import javax.microedition.location.QualifiedCoordinates;
import net.rim.device.api.system.Application;
public class GPS_Location
{
private String log;
double longi;
double lati;
public GPS_Location()
{
new LocationTracker();
}
public boolean onClose()
{
Application.getApplication().requestBackground();
return false;
}
class LocationTracker extends TimerTask
{
private double longitude, latitude;
private Timer timer;
private LocationProvider provider;
Criteria cr;
public LocationTracker()
{
timer = new Timer();
cr= new Criteria();
resetGPS();
timer.schedule(this, 0, 60000);
}
public void resetGPS()
{
try
{
provider = LocationProvider.getInstance(cr);
if(provider != null)
{
/*provider.setLocationListener(null, 0, 0, 0);
provider.reset();
provider = null;*/
provider.setLocationListener(new MyLocationListener(), 3, -1, -1);
}
//provider = LocationProvider.getInstance(null);
} catch(Exception e)
{
}
}
public void run()
{
System.out.println("********************");
}
private class MyLocationListener implements LocationListener
{
public void locationUpdated(LocationProvider provider, Location location)
{
if(location != null && location.isValid())
{
QualifiedCoordinates qc = location.getQualifiedCoordinates();
try
{
lati = location.getQualifiedCoordinates().getLatitude();
System.out.println("********************latitude :: "+lati);
longi = location.getQualifiedCoordinates().getLongitude();
System.out.println("********************longitude ::"+longi);
}
catch(Exception e)
{
}
}
}
public void providerStateChanged(LocationProvider provider, int newState)
{
//LocationTracker.this.resetGPS();
if(newState == LocationProvider.TEMPORARILY_UNAVAILABLE)
{
provider.reset();
provider.setLocationListener(null, 0, 0, -1);
}
}
}
}
}

A Google result (coincidentally Stack Overflow) reveals the API call getLocation(). This may provide you with a starting point for retrieving the longitude and latitude.
Addition; the following may be helpful (from a subsequent Google search using terms based on your comment): http://www.blackberryforums.com/developer-forum/133152-location-api.html. I would quote some of the code, but there is a fair bit of information there. Let's just hope the link remained valid, or you post your solution when found :)

Related

Get GPS Location in IOS 8 using XAMARIN

i am new to Xamarin, i have a code to get GPS location, which is working fine for IOS 6 but for IOS 8 it is not fetching the long. and lat.
//Check for getting current lat/long
CLLocationCoordinate2D toLocation;
private CLLocationManager locationManager;
if (!CLLocationManager.LocationServicesEnabled) {
AppDelegate.currLat = "";
AppDelegate.currLong = "";
gpsFlag = false;
} else {
gpsFlag = true;
locationManager = new CLLocationManager();
locationManager.StartUpdatingLocation();
if (locationManager.Location != null) {
toLocation = locationManager.Location.Coordinate;
AppDelegate.currLat = Convert.ToString (toLocation.Latitude);
AppDelegate.currLong = Convert.ToString (toLocation.Longitude);
}
locationManager.StopUpdatingLocation ();
}
i am using the Universal Template to create Application in Xamarin. i have R&D for IOS 8 GPS location, i got to know that i need to add "NSLocationAlwaysUsageDescription" to info.plist, but i am not getting how to add this.
getting-gps-location-using-core-location-in-ios-8
Please help me how can get the GPS location for IOS 8
public class LocationHelper
{
private static bool _isTracking;
public static bool IsTracking { get { return _isTracking; } }
private static string _longitude;
private static string _latitude;
private static DateTime _lastUpdated;
public static event EventHandler LocationUpdated;
public static CLLocationManager LocationManager { private set; get; }
public static void StartLocationManager(double distanceFilter, double accuracy)
{
LocationManager = new CLLocationManager();
if (LocationManager.RespondsToSelector(new MonoTouch.ObjCRuntime.Selector("requestWhenInUseAuthorization")))
LocationManager.RequestWhenInUseAuthorization();
LocationManager.DistanceFilter = CLLocationDistance.FilterNone;
LocationManager.DesiredAccuracy = accuracy;
LocationManager.LocationsUpdated += LocationManager_LocationsUpdated;
LocationManager.StartUpdatingLocation();
_isTracking = true;
System.Diagnostics.Debug.WriteLine("Location manager started ");
}
public static void StopLocationManager()
{
if (LocationManager != null)
{
LocationManager.LocationsUpdated -= LocationManager_LocationsUpdated;
LocationManager = null;
_isTracking = false;
}
}
public static void Refresh()
{
LocationManager.StopUpdatingLocation();
LocationManager.StartUpdatingLocation();
}
private static void LocationManager_LocationsUpdated(object sender, CLLocationsUpdatedEventArgs e)
{
if (LocationUpdated != null)
LocationUpdated(null, null);
UpdateLocation(e.Locations[e.Locations.Length - 1]);
}
private static void UpdateLocation(CLLocation location)
{
_longitude = location.Coordinate.Longitude.ToString();
_latitude = location.Coordinate.Latitude.ToString();
_lastUpdated = DateTime.Now;
}
public static LocationResult GetLocationResult()
{
return new LocationResult(_latitude, _longitude, _lastUpdated);
}
public class LocationResult
{
public DateTime UpdatedTime { private set; get; }
public string Latitude { private set; get; }
public string Longitude { private set; get; }
public LocationResult(string latitude, string longitude, DateTime updated)
{
UpdatedTime = updated;
Latitude = latitude;
Longitude = longitude;
}
}
}
This works in iOS8I'm using this static class, every time before taking coordinates I'm calling Refresh() I'm cant find thread where i found this solution but this causes to return location immediately, and then call to GetLocationResult() to get location and when u finished with locationManager call StopLocationManager()
When you create a new instance of CLLocationmanager it is extremely important that you call the following:
manager = new CLLocationManager();
1.) manager.RequestWhenInUseAuthorization (); //This is used if you are doing anything in the foreground.
2.) manager.RequestAlwaysAuthorization ();// This is used if you want to scan in the background
Of course these are iOS 8 only methods so makes sure to do a version check with: UIDevice.CurrentDevice.CheckSystemVersion (8, 0);
This isn’t enough though to prompt your user for access to location. You will need to now modify your Info.plist! You will need to add a new string entry called NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription. Then you can specify the message you want to prompt your user with when attempting to get location

Blackberry issue on cell site GPS tracking

In my BB app, I try to fetch the location using the cell site.
But it always throws a Location exception:
Timed out while waiting for Geolocation.m=0
Here is my code
Criteria criteria = new Criteria();
criteria.setHorizontalAccuracy(Criteria.NO_REQUIREMENT);
criteria.setVerticalAccuracy(Criteria.NO_REQUIREMENT);
criteria.setCostAllowed(true);
criteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_LOW);
LocationProvider provider = LocationProvider.getInstance(criteria);
Location location = provider.getLocation(-1);
QualifiedCoordinates qualifiedCoordinates = location.getQualifiedCoordinates();
double latitude = qualifiedCoordinates.getLatitude();
double longitude = qualifiedCoordinates.getLongitude();
But if i change the parameters to
criteria.setHorizontalAccuracy(50);
criteria.setVerticalAccuracy(50);
criteria.setCostAllowed(true);
criteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_HIGH);
the assisted GPS works fine and I will get the correct location of device.
class LocationTracker{
private LocationProvider provider;
Criteria cr;
public LocationTracker() {
cr= new Criteria();
resetGPS();
}
public void resetGPS(){
try {
provider = LocationProvider.getInstance(cr);
if(provider != null) {
provider.setLocationListener(new MyLocationListener(),60, -1, -1);
}
}
catch (LocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class MyLocationListener implements LocationListener {
public void locationUpdated(LocationProvider provider, Location location){
if(location != null && location.isValid()){
QualifiedCoordinates qc = location.getQualifiedCoordinates();
try {
LAT = location.getQualifiedCoordinates().getLatitude();
System.out.println("=============================lattitude :: "+LAT);
LONG= location.getQualifiedCoordinates().getLongitude();
System.out.println("==================================longitude ::"+LONG);
}
catch(Exception e){
}
}
}
public void providerStateChanged(LocationProvider provider, int newState){
if(newState == LocationProvider.TEMPORARILY_UNAVAILABLE){
provider.reset();
provider.setLocationListener(null, 0, 0, -1);
}
}
}
Like vijay, you can register to location update.
If you still want to use your solution, you have to be sure that
- It is threaded (and not just only not to get an ANR, it is a requirement)
- You have a SIM card with a Blackberry option
- You run on at least OS 5.0.0

How to get current location in blackberry device?

In simulator my gps code work fine. But when I install my app in device I can't get current latitude and longitude.
When I send lat long from simulator it get proper lat long which is send through simulator. I don't know why is not working in device?
I have already enable from Option > Advance option > gps > gps servce and set Location ON.
Is there any other setting for get current location in device?
private boolean currentLocation() {
boolean retval = true;
try {
LocationProvider lp = LocationProvider.getInstance(null);
if (lp != null) {
lp.setLocationListener(new LocationListenerImpl(), interval, 1, 1);
} else {
// GPS is not supported, that sucks!
// Here you may want to use UiApplication.getUiApplication() and post a Dialog box saying that it does not work
retval = false;
}
} catch (LocationException e) {
System.out.println("Error: " + e.toString());
}
return retval;
}
private class LocationListenerImpl implements LocationListener {
public void locationUpdated(LocationProvider provider, Location location) {
if (location.isValid()) {
heading = location.getCourse();
longitude = location.getQualifiedCoordinates().getLongitude();
latitude = location.getQualifiedCoordinates().getLatitude();
altitude = location.getQualifiedCoordinates().getAltitude();
speed = location.getSpeed();
// This is to get the Number of Satellites
String NMEA_MIME = "application/X-jsr179-location-nmea";
satCountStr = location.getExtraInfo("satellites");
if (satCountStr == null) {
satCountStr = location.getExtraInfo(NMEA_MIME);
}
// this is to get the accuracy of the GPS Cords
QualifiedCoordinates qc = location.getQualifiedCoordinates();
accuracy = qc.getHorizontalAccuracy();
}
}
Try this code
Thread thread = new Thread(new Runnable() {
public void run() {
bCriteria = new BlackBerryCriteria();
if (GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_CELLSITE)) {
bCriteria.setMode(GPSInfo.GPS_MODE_CELLSITE);
} else if (GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_ASSIST)) {
bCriteria.setMode(GPSInfo.GPS_MODE_ASSIST);
} else if (GPSInfo
.isGPSModeAvailable(GPSInfo.GPS_MODE_AUTONOMOUS)) {
bCriteria.setMode(GPSInfo.GPS_MODE_AUTONOMOUS);
} else {
bCriteria.setCostAllowed(true);
bCriteria
.setPreferredPowerConsumption(Criteria.POWER_USAGE_LOW);
}
try {
bProvider = (BlackBerryLocationProvider) BlackBerryLocationProvider
.getInstance(bCriteria);
if (bProvider != null) {
bProvider.setLocationListener(new handleGPSListener(),
-1, -1, -1);
try {
bLocation = (BlackBerryLocation) bProvider
.getLocation(60);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (LocationException lex) {
lex.printStackTrace();
return;
}
}
});
thread.start();
then implement Location Listener in the class
public class handleGPSListener implements LocationListener {
public void locationUpdated(LocationProvider provider, Location location) {
if (location.isValid()) {
}
}
public void providerStateChanged(LocationProvider provider, int newState) {
}
}

myReverseGeocode is not starting.

In below code when i call myReverseGeocode address = new myReverseGeocode(latitude, longitude); , gpsData.append(address.temp); always show "null"
public HelloBlackBerryScreen() {
super( MainScreen.VERTICAL_SCROLL | MainScreen.VERTICAL_SCROLLBAR );
setTitle( "Get Address" );
ButtonField buttonField_1 = new ButtonField( "Get GPS", ButtonField.CONSUME_CLICK | ButtonField.FIELD_RIGHT );
add( buttonField_1 );
buttonField_1.setChangeListener( new FieldChangeListener() {
public void fieldChanged( Field arg0, int arg1 ) {
Criteria c = new Criteria();
try {
LocationProvider lp = LocationProvider.getInstance(c);
if( lp!=null )
{
lp.setLocationListener(new LocationListenerImpl(), 3, 1, 1);
myReverseGeocode address = new myReverseGeocode(latitude, longitude);
gpsData.append(address.temp);
myloc = gpsData.toString();
}
} catch (LocationException le) {
;
}
myReverseGeocode.java
package mypackage;
import javax.microedition.location.AddressInfo;
import javax.microedition.location.Landmark;
import net.rim.device.api.lbs.Locator;
import net.rim.device.api.lbs.LocatorException;
public class myReverseGeocode {
private Thread reverseGeocode;
public AddressInfo addrInfo = null;
String temp;
public myReverseGeocode(final double lt, final double ln)
{
Runnable thread = new Runnable()
{
public void run()
{
int latitude = (int)(lt * 100000);
int longitude = (int)(ln * 100000);
try
{
Landmark[] results = Locator.reverseGeocode(latitude, longitude, Locator.ADDRESS );
if ( results != null && results.length > 0 )
temp = "inside if";
else
temp = "in else";
}
catch ( LocatorException lex )
{
}
}
};
reverseGeocode = new Thread(thread);
reverseGeocode.setPriority(Thread.MIN_PRIORITY);
reverseGeocode.start();
}
}
You always get temp as null because you ask for it almost immediatelly after the Thread (that is started in constructor of the myReverseGeocode) has been started. You need to redesign your myReverseGeocode to udate the UI of the screen after an actual temp value is got.

Blackberry GPS returns zero for longitude and latitude

I am using the following class to get GPS location from blackberry, but I am always getting zero longtude and latitude values. Why is that?
public class LocationTracker extends TimerTask {
private double longitude;
private double latitude;
private double altitude;
private LocationProvider lp;
public LocationTracker() {
super();
// Set criteria for selecting a location provider:
Criteria cr = new Criteria();
cr.setCostAllowed(true);
cr.setPreferredResponseTime(60);
cr.setHorizontalAccuracy(Criteria.NO_REQUIREMENT);
cr.setVerticalAccuracy(Criteria.NO_REQUIREMENT);
cr.setAltitudeRequired(true);
cr.isSpeedAndCourseRequired();
cr.isAddressInfoRequired();
cr.setPreferredPowerConsumption(Criteria.POWER_USAGE_HIGH);
try {
LocationProvider lp = LocationProvider.getInstance(cr);
Location location = null;
try {
location = lp.getLocation(-1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (LocationException e){
System.out.println(e.toString());
}catch(Exception e ){
System.out.println(e.toString());
}
longitude = location.getQualifiedCoordinates().getLongitude();
latitude = location.getQualifiedCoordinates().getLatitude();
altitude = location.getQualifiedCoordinates().getAltitude();
if (lp != null) {
lp.reset();
lp.setLocationListener(null, -1, -1, -1);
lp = LocationProvider.getInstance(cr);
lp.setLocationListener(new MyLocationListener(), 2, -1, -1);
}
System.out.println("Lon" + longitude + " Lat "+ latitude);
} catch (LocationException le) {
System.out.println(le.toString());
}catch(Exception e ){
System.out.println(e.toString());
}
}
public void run() {
}
public double getLongitude() {
return longitude;
}
public double getLatitude() {
return latitude;
}
public double getAltitude() {
return altitude;
}
private class MyLocationListener implements LocationListener {
public void locationUpdated(LocationProvider provider, Location location) {
if (location != null && location.isValid()) {
QualifiedCoordinates qc = location.getQualifiedCoordinates();
try {
latitude = qc.getLatitude();
longitude = qc.getLongitude();
altitude = qc.getAltitude();
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
public void providerStateChanged(LocationProvider provider, int newState) {
// TODO: if provider was disabled, then disable reporting
}
}
}
Did you check gps status from settings? If it is working try to set timeout value about 300 seconds instead of -1.
The LocationProvider may return a Location object which has isValid() false. This is done to provide additional informaton via the getExtraInfo() method.

Resources