current location from CoreLocation - iphone-sdk-3.0

I have an App which launches the google Map App. The code is:
UIApplication *app = [UIApplication sharedApplication];
[app openURL:[[NSURL alloc] initWithString: #"http://maps.google.com/maps?daddr=Obere+Laube,+Konstanz,+Germany&saddr="]];
The saddr= should be the current location. I get the current location with
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(#"%f,%f", [newLocation coordinate]);
The Log displays the correct coordinates like
2010-04-05 15:33:25.436 deBordeaux[60657:207] 37.331689,-122.030731
I didn't find the right way to transmit the coordinates to the url-string. Does someone can give me a hint how-to?
Hmmm, I had the entry in my .h
In my method I use "newLocation" instead your "location". The code is:
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
NSLog(#"%f,%f", [newLocation coordinate]);
NSLog(#"%f", [newLocation coordinate].latitude);
storedLocation = [newLocation coordinate];
NSLog(#"Standort neu String: %#", storedLocation);
As result I get :
2010-04-05 20:28:44.397 deBordeaux[64179:207] 37.331689,-122.030731
2010-04-05 20:28:44.398 deBordeaux[64179:207] 37.331689
Program received signal: “EXC_BAD_ACCESS”.

You shouldn't use addr parameter of the URL but ll.
You should pass latitude and longitude as
http://maps.google.com/maps?daddr=Obere+Laube,+Konstanz,+Germany&ll=37.331689,-122.030731
and you can obtain them from the CLocation throught
[location coordinate].latitude
[location coordinate].longitude
EDIT:
First of all you can directly store an object of type CLLocationCoordinate2D and then convert it to a NSString when you need:
// in your .h
CLLocationCoordinate2D storedLocation;
// in your method
storedLocation = [location coordinate];
// when you want to ask google maps
[NSString stringWithFormat:#"http://maps.google.com/maps?daddr=Obere+Laube,+Konstanz,+Germany&ll=%f,%f", storedLocation.latitude, storedLocation.longitude];
Mind that CLLocationCoordinate2D is defined as
typedef struct {
CLLocationDegrees latitude;
CLLocationDegrees longitude;
} CLLocationCoordinate2D;
where you have typedef double CLLocationDegrees

Related

Current Latitude Longitude on Google Map

I am using below code to get current lat long in iOS 8.
.h
#interface DirectionViewController : UIViewController<CLLocationManagerDelegate,GMSMapViewDelegate>
{
CLLocationManager *locationManager;
}
#property (nonatomic, retain) CLLocationManager *locationManager;
.m
#synthesize locationManager;
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
// Configure the new event with information from the location
CLLocationCoordinate2D coordinate = [location coordinate];
NSString *latitude = [NSString stringWithFormat:#"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", coordinate.longitude];
NSLog(#"dLatitude : %#", latitude);
NSLog(#"dLongitude : %#",longitude);
But here, I am getting 0.00000 value for both latitude and longitude.
Can anybody help me here. How to get current lat long in iOS 8?
Thanks in advance!
AppDelegte.h
#interface AppDelegate : UIResponder <UIApplicationDelegate,CLLocationManagerDelegate>
{
CLLocation *currentLocation;
}
#property (strong, nonatomic) CLLocationManager *locationManager;
#property (nonatomic, assign) CLLocationCoordinate2D currentLocationCoordinate;
Appdelget.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
locationManager = [[CLLocationManager alloc]init]; // initializing locationManager
locationManager.delegate = self; // we set the delegate of locationManager to self.
locationManager.desiredAccuracy = kCLLocationAccuracyBest; // setting the accuracy
[locationManager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
CurrentLatitude=newLocation.coordinate.latitude;
CurrentLongitude=newLocation.coordinate.longitude;
NSLog(#"%f",CurrentLatitude);
NSLog(#"%f",CurrentLongitude);
[locationManager stopUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Failed to Get Your Location" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
.Plsit add
NSLocationAlwaysUsageDescription
NSLocationWhenInUseUsageDescription
You're not using the proper method to get your coordinates.
once you call startUpdatingLocation, it calls the location manager methods (that you must implement in order for this to work).
There are two of them, [locationManager:didFailWithError:][1]
and [-locationManager:didUpdateLocations:][2]. You should have warnings asking you to add those methods in your .m, with the proper spelling if you haven't done it yet.
didUpdateLocation is called every X seconds and returns coordinates. You have to build your coordinate strings in this very specific method, where the coordinates are set.
From what I could gather,
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations
Will give you an array of CLLocation objects containing the location data.
This array always contains at least one object representing the current location.
If updates were deferred or if multiple locations arrived before they could be delivered, the array may contain additional entries.
The objects in the array are organized in the order in which they occurred. Therefore, the most recent location update is at the end of the array.
This means you'll have to get the lastObject of that array for the most recent location.
Here is an example i've found on the web, for what the inside of that method could look. :
CLLocation *newLocation = [locations lastObject];
CLLocation *oldLocation;
if (locations.count > 1) {
oldLocation = [locations objectAtIndex:locations.count-2];
} else {
oldLocation = nil;
}
NSLog(#"didUpdateToLocation %# from %#", newLocation, oldLocation);
MKCoordinateRegion userLocation = MKCoordinateRegionMakeWithDistance(newLocation.coordinate, 1500.0, 1500.0);
[regionsMapView setRegion:userLocation animated:YES];
Make sure to ask for the different permissions beforehand, and that you have them.
Also note that this method is only available since iOS5 and is different in the previous versions. Though it is very unlikely that you still support iOS5, I thought I should mention it.

iOS7 CLLocationManager pauses updates and won't resume

I have a chunk of code that I can run in iOS simulation and get continuous locations updates, but when I run it on an iPad it seems to stall after the third update. I have tried to change the activityType to other or and set things that might be causing it to pause updates, but those didn't seem to help. It's also not clear to my why it's stopping in real life and not in the simulation.
I did try stopping updates on every update followed by a startUpdates and this did seem to work, but that strikes me as a bad way to behave. Does anyone have additional recommendations or experience with this kind of issue.
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#interface ViewController () <CLLocationManagerDelegate>
#property (nonatomic, strong) CLLocationManager *myLocationManager;
#end
#implementation ViewController
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
for (int locIndex = 0; locIndex < locations.count; locIndex++)
{
CLLocation *newLocation = [locations objectAtIndex:locIndex];
NSLog(#"Latitude = %f", newLocation.coordinate.latitude);
NSLog(#"Longitude = %f", newLocation.coordinate.longitude);
}
CLLocationDistance distance = 0;
NSTimeInterval timeout = 1;
[manager allowDeferredLocationUpdatesUntilTraveled:distance timeout:timeout];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation{
CLLocationDistance distance = 0;
NSTimeInterval timeout = 1;
[manager allowDeferredLocationUpdatesUntilTraveled:distance timeout:timeout];
/* We received the new location */
NSLog(#"Latitude = %f", newLocation.coordinate.latitude);
NSLog(#"Longitude = %f", newLocation.coordinate.longitude);
//[self.myLocationManager stopUpdatingLocation];
//[self.myLocationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error{
/* Failed to receive user's location */
NSLog(#"******************************************************");
NSLog(#"************** FAILED TO RECEIVE LOCATION ************");
NSLog(#"******************************************************");
}
- (void)viewDidLoad {
[super viewDidLoad];
if ([CLLocationManager locationServicesEnabled]){
self.myLocationManager = [[CLLocationManager alloc] init];
self.myLocationManager.delegate = self;
//self.myLocationManager.pausesLocationUpdatesAutomatically = NO;
//self.myLocationManager.activityType = CLActivityTypeOther;
[self.myLocationManager startUpdatingLocation];
//self.myPeripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil options:nil];
} else {
/* Location services are not enabled.
Take appropriate action: for instance, prompt the
user to enable the location services */
NSLog(#"Location services are not enabled");
}
}
Pausing is used when the user has forgotten taht the GPS is active. To prevent the GPS to drain the battery the gps is then stoped and newer turned on again, before the app is started again.
You should catch the pause call and ask the user if the location updates should continue or not.

Circle overlay follow user location

How can i make my custom circle overlay follow as a subview the current user location in real time? I have managed to display my circle overlay and get to the center of userlocation but when user moves (gps) the overlay stays still and does not followuser. How do i fix that? Thank you in advance..
- (void)viewDidLoad {
[super viewDidLoad];
[self.mapView setRegion:MKCoordinateRegionMake(self.location.coordinate, MKCoordinateSpanMake(0.02, 0.02))];
[self configureOverlay];
[[self locationManager] startUpdatingLocation];
}
in configureOverlay:
CircleOverlay *overlay = [[CircleOverlay alloc] initWithCoordinate:self.location.coordinate radius:self.radius];
[self.mapView addOverlay:overlay];
GeoQueryAnnotation *annotation = [[GeoQueryAnnotation alloc] initWithCoordinate:self.location.coordinate radius:self.radius];
[self.mapView addAnnotation:annotation];
I also tried using:
CLLocation *location = _locationManager.location;
CLLocationCoordinate2D coordinate = [location coordinate];
and replacing coordinate with self.location.coordinate
any advise would be appreciated.Thank you
Tell your class you are going to implement CLLocationManagerDelegate
#interface YourClass () <CLLocationManagerDelegate>
Then add the following methods:
#pragma mark CLLocationManagerDelegate Methods
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
//You can change the overlay coordinates here. Even with an animation if you want.
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSString *errorType = (error.code == kCLErrorDenied) ? #"Access Denied" : #"Unknown Error";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error getting Location"message:errorType delegate:nil cancelButtonTitle:#"Okay" otherButtonTitles:nil];
[alert show];
}
The locationManager:didUpdateToLocation... method will be triggered each time the location manager detects a change in the user's position.
Cheers.
EDIT
I forgot about something very important. In your viewDidLoad method add your class as the delegate:
self.locationmanager.delegate = self;

problem in getting the altitude value using CLLocationManager in iphone sdk

I am using the code as I specified below to get the altitude value
-(void)awakeFromNib {
locmanager = [[CLLocationManager alloc] init];
[locmanager setDelegate:self];
[locmanager setDesiredAccuracy:kCLLocationAccuracyBest];
[locmanager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
heightMesurement.text = [NSString stringWithFormat: #"%.2f m", newLocation.altitude];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
heightMesurement.text = #"0.00 m";
}
The didUpdateToLocation method is calling and I am getting the altitude value as null when I print heightMesurement.text.
Can anyone give me idea why this happening like this and how to rectify it.
Thanks to all,
Monish.

Accessing iPhone's current location

How can I store the latitude and longitude coordinates of the iPhone's current location into two different float variables?
This tutorial will help you do exactly that.
Here is the relevant code from the tutorial that you would be interested in:
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
int degrees = newLocation.coordinate.latitude;
double decimal = fabs(newLocation.coordinate.latitude - degrees);
int minutes = decimal * 60;
double seconds = decimal * 3600 - minutes * 60;
NSString *lat = [NSString stringWithFormat:#"%d° %d' %1.4f\"",
degrees, minutes, seconds];
latLabel.text = lat;
degrees = newLocation.coordinate.longitude;
decimal = fabs(newLocation.coordinate.longitude - degrees);
minutes = decimal * 60;
seconds = decimal * 3600 - minutes * 60;
NSString *longt = [NSString stringWithFormat:#"%d° %d' %1.4f\"",
degrees, minutes, seconds];
longLabel.text = longt;
}
Chetan's answer is excellent and will give you the lat and long in degrees. Just in case you're only interested in storing the lat and long in units that you can then use for comparison with other locations you might just do the following:
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
CLLocationDegrees latitude = newLocation.coordinate.latitude;
CLLocationDegrees longitude = newLocation.coordinate.longitude;
...
}
If you want to keep these then you'd want to provide some sort of storage for the values. Otherwise they'll go out of scope at the end of the method.
Note that CLLocationDegrees is merely a double with a pretty name.
Keep in mind that a CLLocation.coordinate is a neat struct that you may store as a CLLocationCoordinate2D - much more elegant to keep these values together as they retain a little more context.
You can initialize a CLLocationManager to find a point and reference it afterwords (note this initialization is borrowed from another post).
CLLocationManager *curLocationManager = [[CLLocationManager alloc] init];
curLocationManager.delegate = self; //SET YOUR DELEGATE HERE
curLocationManager.desiredAccuracy = kCLLocationAccuracyBest; //SET THIS TO SPECIFY THE ACCURACY
[curLocationManager startUpdatingLocation];
//NSLog(#"currentLocationManager is %#", [curLocationManager.location description]);
[curLocationManager stopUpdatingLocation];
//NSLog(#"currentLocationManager is now %#", [curLocationManager.location description]);
//NSLog(#"latitude %f", curLocationManager.location.coordinate.latitude);
//NSLog(#"longitude %f", curLocationManager.location.coordinate.longitude);
double latitude = curLocationManager.location.coordinate.latitude;
double longitude = curLocationManager.location.coordinate.longitude;
Note you will also need to include (CLLocationManager *)locationManager and (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation and you should include (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
Use following code to show current location in MKMapView and for setting Zoom Level in iPhone App.
1) Add MApKit and CoreLocation Framework in your project.
2) Use following code in ViewController.h file:
#import "mapKit/MapKit.h"
#import "CoreLocation/CoreLocation.h"
#interface ViewController : UIViewController<MKMapViewDelegate, CLLocationManagerDelegate>
{
MKMapView *theMapView;
CLLocationManager *locationManager;
CLLocation *location;
float latitude, longitude;
}
3) Add following code on viewDidLoad method:
// Add MKMapView in your View
theMapView=[[MKMapView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
theMapView.delegate=self;
[self.view addSubview:theMapView];
// Create an instance of CLLocationManager
locationManager=[[CLLocationManager alloc] init];
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
locationManager.delegate=self;
[locationManager startUpdatingLocation];
// Create an instance of CLLocation
location=[locationManager location];
// Set Center Coordinates of MapView
theMapView.centerCoordinate=CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);
// Set Annotation to show current Location
MKPointAnnotation *annotaionPoint=[[MKPointAnnotation alloc] init];
annotaionPoint.coordinate=theMapView.centerCoordinate;
annotaionPoint.title=#"New Delhi";
annotaionPoint.subtitle=#"Capital";
[theMapView addAnnotation:annotaionPoint];
// Setting Zoom Level on MapView
MKCoordinateRegion coordinateRegion;
coordinateRegion.center = theMapView.centerCoordinate;
coordinateRegion.span.latitudeDelta = 1;
coordinateRegion.span.longitudeDelta = 1;
[theMapView setRegion:coordinateRegion animated:YES];
// Show userLocation (Blue Circle)
theMapView.showsUserLocation=YES;
4) Use following Location to updateUserLocation
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
latitude=userLocation.coordinate.latitude;
longitude=userLocation.coordinate.longitude;
theMapView.centerCoordinate=CLLocationCoordinate2DMake(latitude, longitude);
MKPointAnnotation *annotationPoint=[[MKPointAnnotation alloc] init];
annotationPoint.coordinate=theMapView.centerCoordinate;
annotationPoint.title=#"Moradabad";
annotationPoint.subtitle=#"My Home Town";
}