Get current location using CLLocationCoordinate2D - iphone

I am trying to get current location of user using CLLocationCoordinate2D. I want the values in the format like
CLLocationCoordinate2D start = {-28.078694,153.382844 };
So that I can use them like following:
NSString *urlAddress = [NSString
stringWithFormat:#"http://maps.google.com/?saddr=%1.6f,%1.6f&daddr=%1.6f,%1.6f",
start.latitude, start.longitude,
destination.latitude, destination.longitude];
I used
CLLocation *location = [[CLLocation alloc]init ];
CLLocationDegrees currentLatitude = location.coordinate.latitude;
CLLocationDegrees currentLongitude = location.coordinate.longitude;
to get current lat & long.
But I am getting 0.000 for both when I try to test. I am testing on iPhone 4s.
If there is any sample code, it will be great.

Add CoreLocation framework first and then use the following code...and your viewController must implement CLLocationManagerDelegate
-(void)findCurrentLocation
{
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
if ([locationManager locationServicesEnabled])
{
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
}
CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];
NSString *str=[[NSString alloc] initWithFormat:#" latitude:%f longitude:%f",coordinate.latitude,coordinate.longitude];
NSLog(#"%#",str);
}

in AppDelegate.h declare following variable. and implement
CLLocationManagerDelegate delegate.
CLLocationManager *locationManager;
CLLocation *currentLocation;
in AppDelegate.h.m file write following code.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
self.currentLocation = newLocation;
self.currentLat = newLocation.coordinate.latitude;
self.currentLong = newLocation.coordinate.longitude;
}

You need to use CLLocationManager to get a user's location. CLLocation is only a class of objects used to represent locations, it can't get user location by it self.
For more details and example, please follow to Apple docs on Location Awareness Programming.

CLLocationCoordinate2D location = [[[mapview userLocation] location] coordinate];
NSLog(#"Location found from Map: %f %f",location.latitude,location.longitude);
and also refer the link(without mapview0
https://developer.apple.com/library/ios/#samplecode/LocateMe/Introduction/Intro.html

use location manager to get lat and long, follow this tutorial for sample code http://www.edumobile.org/iphone/miscellaneous/how-to-get-current-latitude-and-longitude-in-iphone/

-(void)findCurrentLocation
{
if ([CLLocationManager locationServicesEnabled])
{
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
[self setLocation:[[manager location] coordinate]];
}

Related

Not getting current user location

in .h file
#import <MapKit/MapKit.h>
#interface FirstViewController : UIViewController <MKMapViewDelegate,MKReverseGeocoderDelegate,CLLocationManagerDelegate>
{
}
in .m file
-(void)viewDidLoad
{
CLLocationManager *locationManager = [[[CLLocationManager alloc] init] autorelease];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
[super viewDidLoad];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
MKReverseGeocoder *geoCoder = [[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate];
geoCoder.delegate = self;
[geoCoder start];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"locationManager:%# didFailWithError:%#", manager, error);
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
MKPlacemark * myPlacemark = placemark;
NSString *kABPersonAddressCityKey;
NSString *city = [myPlacemark.addressDictionary objectForKey:(NSString*) kABPersonAddressCityKey];
lblAddress.text = city;
NSLog(#"city detail is:--> %#",city);
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
{
NSLog(#"reverseGeocoder:%# didFailWithError:%#", geocoder, error);
}
This is the code which I have done to get the current location of user & print it in the label.
But the CLLocationManager delegate method (which are written above) is not called & I am not able to get the current address.
Please help me out.
Where I am doing mistake...? guide me.
Thanks.
Instead of autoreleasing the CLLocationManager instance, assign it to an ivar in your class. Then release it in -dealloc as usual (or in one of the delegate methods if you don't need it any longer).
I suspect your location manager is getting deallocated on the next turn of the run loop before having an opportunity to fire off its delegate methods.
In your method viewDidLoad:
-(void)viewDidLoad
{
CLLocationManager *locationManager = [[[CLLocationManager alloc] init] autorelease];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
myMapView.showsUserLocation = YES; // add this line
[super viewDidLoad];
}
And you are done!!!

Current Location in the Simulator

Im doing an app in which i have to find the current location of the user.can i get the current location of the user in the iOS 5 simulator by using CLLocationmanager?
xcode - Edit Scheme - Run you.app - Option
check Allow Location Simulation, then select "Default Location"
Add GPX File to Project
the format like this
In Xcode, you can select the location to simulate using a small button above the console.
- (void)viewDidLoad{
[super viewDidLoad];
self.title = #"MapView";
self.navigationController.navigationBarHidden = NO;
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
}
- (void) loadPin {
iCodeBlogAnnotation *appleStore1;
CLLocationCoordinate2D workingCoordinate;
workingCoordinate.latitude = [latitude doubleValue];
workingCoordinate.longitude = [longitude doubleValue];
appleStore1 = [[iCodeBlogAnnotation alloc] initWithCoordinate:workingCoordinate];
[appleStore1 setTitle:[NSString stringWithFormat:#"Default Point"]];
//[appleStore1 setSubtitle:[NSString stringWithFormat:#"Distance %.2f Miles",miles]];
[appleStore1 setAnnotationType:iCodeBlogAnnotationTypeEDU];
[mapView addAnnotation:appleStore1];
[(MKMapView*)self.mapView selectAnnotation:appleStore1 animated:NO];
MKCoordinateRegion region;
region.center.latitude = [latitude doubleValue];
region.center.longitude = [longitude doubleValue];
region.span.latitudeDelta = .5;
region.span.longitudeDelta = .5;
[mapView setRegion:region animated:YES];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
latitude = [[NSString alloc] initWithFormat:#"%f", newLocation.coordinate.latitude];
longitude = [[NSString alloc] initWithFormat:#"%f", newLocation.coordinate.longitude];
[locationManager stopUpdatingLocation];
if (latitude > 0) {
[self loadPin];
}
}

How can I get GPS location in Iphone

Can you tell me, how can I get GPS location in iPhone.
Thanks.
Implement CLLocationManagerDelegate and write this function and call this in viewDidLoad Method of your viewController.
-(void)startLocationManager
{
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate=self;
locationManager.desiredAccuracy=kCLLocationAccuracyBestForNavigation;
[locationManager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
CLLocationCoordinate2D coordinate = [newLocation coordinate];
double dblLatitude = coordinate.latitude;
double dblLongitude = coordinate.longitude;
}
If you are using CLLocationmanager, make sure you check to see if location Service is enabled first. I would do this to get the current location:
if ([CLLocationManager locationServicesEnabled])
{
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
[locationManager startUpdatingLocation];
CLLocationCoordinate2D *currentLocation = locationManager.location;
[locationManager stopUpdatingLocation];
[locationManager release];
}
If you are using mapView, you could get current location using:
[mapView setShowsUserLocation:YES];
CLLocationCoordinate2D *currentLocation = mapView.userLocation.coordinate;
You use CoreLocation framework.
Here you can get sample code http://mobileorchard.com/hello-there-a-corelocation-tutorial/

Core Location returning 00

Here's the full method, I didn't put the second half originally because I know it works:
-(void)showDirections
{
locationManager = [[CLLocationManager alloc] init];
[locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
[locationManager setDelegate:self];
CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];
NSNumber *myLatitude = [NSNumber numberWithDouble:coordinate.latitude];
NSNumber *myLongitude = [NSNumber numberWithDouble:coordinate.longitude];
double myLatitude2 = [myLatitude doubleValue];
double myLongitude2 = [myLongitude doubleValue];
NSArray *array = [dataHold objectForKey:#"Subtree"];
NSString *latitude = [NSString stringWithFormat:#"%#",[array objectAtIndex:4]];
NSString *longitude = [NSString stringWithFormat:#"%#",[array objectAtIndex:5]];
double clubLatitude = [latitude doubleValue];
double clubLongitude = [longitude doubleValue];
CLLocationCoordinate2D start = { myLatitude2, myLongitude2};
CLLocationCoordinate2D destination = { clubLatitude, clubLongitude};
NSString *googleMapsURLString = [NSString stringWithFormat:#"http://maps.google.com/?saddr=%1.6f,%1.6f&daddr=%1.6f,%1.6f",start.latitude, start.longitude, destination.latitude, destination.longitude];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:googleMapsURLString]];
}
Two issues:
1) You are doing a NSNumber box/unbox cycle that has no use whatsoever
2) Core Location is asynchronous, therefore you cannot return the user's location straight away, you must use the delegate method(s) to retrieve the location if/when it is available.
Here's an example of how it should work:
-(void)showDirections
{
locationManager = [[CLLocationManager alloc] init];
[locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
[locationManager setDelegate:self];
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
CLLocationCoordinate2D coord = [newLocation coordinate];
NSArray *array = [dataHold objectForKey:#"Subtree"];
NSString *latitude = [NSString stringWithFormat:#"%#",[array objectAtIndex:4]];
NSString *longitude = [NSString stringWithFormat:#"%#",[array objectAtIndex:5]];
double clubLatitude = [latitude doubleValue];
double clubLongitude = [longitude doubleValue];
NSString *googleMapsURLString = [NSString stringWithFormat:#"http://maps.google.com/?saddr=%1.6f,%1.6f&daddr=%1.6f,%1.6f", coord.latitude, coord.longitude, clubLatitude, clubLongitude];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:googleMapsURLString]];
}
The fourth line of your code is where the problem begins. You cannot get the location instantly, you will need to wait until the location services notify the delegate that a location is available. I will add some comments to your code to explain:
-(void)showDirections
{
locationManager = [[CLLocationManager alloc] init];
[locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
[locationManager setDelegate:self];
// this is not where you should be looking
CLLocation *location = [locationManager location];
// the rest of this function is not included in this example ...
}
Since you set the delegate as "self", the current class but implement the "CLLocationManagerDelegate" protocol, which defines the following two functions:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { /* */ }
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { /* */ }
That is where you will get a location provided to you.
Dont forget to update your class definition like so:
#interface MyClass : NSObject <CLLocationManagerDelegate> {
And as a side note, it seems like you do not fully understand delegates and the purpose that they serve, which is fine if you are new to Objective-C, but getting more familiar with them will certainly make your life a bit easier.
Some other helpful stuff:
A CoreLocation Tutorial (covers what you are trying to do)

How do I get the current location from the location manager?

i want my app to get the exact location (longitude and latitude) of where he is as every second, it is possible ? i have this code so far, every 3 second the app get the current location but it doesnt update if i move...
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
NSLog(#"lol");
[locationManager stopUpdatingLocation];
if (wtf == 2) {
[[NSUserDefaults standardUserDefaults] setObject:newLocation forKey:#"old"];
NSLog(#"wtf");
wtf =0;
}
oldLocation = [[NSUserDefaults standardUserDefaults] objectForKey:#"old"];
double rep = [oldLocation distanceFromLocation:newLocation];
NSString *label1 = [NSString stringWithFormat:#"%2.90f",oldLocation.coordinate.latitude];
NSString *label2 = [NSString stringWithFormat:#"%2.90f",newLocation.coordinate.latitude];
if ([label1 isEqual:label2]) {
NSLog(#"penis");
}
labelm.text = label1;
labelkm.text = label2;
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
}
-(void)actualise{
[locationManager startUpdatingLocation];
}
- (void)viewDidLoad {
[super viewDidLoad];
wtf = 2;
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:#selector(actualise) userInfo:nil repeats:YES];
}
/*
Use this code to initialize and start the location manager:
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
[locationManager startUpdatingLocation];
And implement didUpdateToLocation like this:
- (void) locationManager:(CLLocationManager*)manager didUpdateToLocation:(CLLocation*)newLocation fromLocation:(CLLocation*) oldLocation
{
// This will be called every time the device has any new location information.
}
There is no need to use any timers.