如何使用CoreLocation查找当前位置

时间:2011-06-29 07:11:32

标签: xcode location core-location cllocationmanager

我需要找到CoreLocation的当前位置,我尝试了多种方法,但到目前为止我的CLLocationManager只返回了0 ..(0.000.00.000)。

这是我的代码(已更新为):

进口

#import <CoreLocation/CoreLocation.h>

声明

IBOutlet CLLocationManager *locationManager;
IBOutlet UILabel *latLabel;
IBOutlet UILabel *longLabel;

功能

- (void)getLocation { //Called when needed
    latLabel.text  = [NSString stringWithFormat:@"%f", locationManager.location.coordinate.latitude]; 
    longLabel.text = [NSString stringWithFormat:@"%f", locationManager.location.coordinate.longitude];
}

- (void)viewDidLoad {
    locationManager = [[CLLocationManager alloc] init];
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
    [locationManager startUpdatingLocation];
}

3 个答案:

答案 0 :(得分:77)

您可以使用CoreLocation找到您的位置:

导入CoreLocation

#import <CoreLocation/CoreLocation.h>

声明CLLocationManager

CLLocationManager *locationManager;

初始化locationManager中的viewDidLoad并创建一个可以return当前位置为NSString的函数:

- (NSString *)deviceLocation {
    return [NSString stringWithFormat:@"latitude: %f longitude: %f", locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude];
}

- (void)viewDidLoad
{
    locationManager = [[CLLocationManager alloc] init];
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
    [locationManager startUpdatingLocation];
}

调用deviceLocation函数将按预期返回位置:

NSLog(@"%@", [self deviceLocation]);

这只是一个例子。在没有用户准备好的情况下初始化CLLocationManager并不是一个好主意。当然,locationManager.location.coordinate可以用来在latitude初始化后随意获取longitudeCLLocationManager

不要忘记在Build Phases选项卡(CoreLocation.framework)下的项目设置中添加Targets->Build Phases->Link Binary

答案 1 :(得分:15)

使用CLLocationManager,您无需立即获取位置信息。获取位置信息的GPS和其他设备可能未初始化。他们可能需要一段时间才能获得任何信息。相反,您需要创建一个响应locationManager:didUpdateToLocation:fromLocation:的委托对象,然后将其设置为位置管理器的委托。

请参阅here

答案 2 :(得分:-2)

您可以在此处显示带注释详细信息的当前位置

ViewController.h中的

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>


//My
#import <MapKit/MapKit.h>
#import <MessageUI/MFMailComposeViewController.h>

@interface ViewController : UIViewController<CLLocationManagerDelegate,MKMapViewDelegate,MFMailComposeViewControllerDelegate>
{
    IBOutlet UILabel *lblLatitiude;
    IBOutlet UILabel *lblLongitude;
    IBOutlet UILabel *lblAdress;
}
//My
@property (nonatomic, strong) IBOutlet MKMapView *mapView;


-(IBAction)getMyLocation:(id)sender;

@end
ViewController.m中的

#import "ViewController.h"


@interface ViewController ()

@end

@implementation ViewController{
    CLLocationManager *locationManager;
    CLGeocoder *geocoder;
    CLPlacemark *placemark;
}

@synthesize mapView;

- (void)viewDidLoad
{
    [super viewDidLoad];
    locationManager = [[CLLocationManager alloc] init];
     geocoder = [[CLGeocoder alloc] init];

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *defaultsDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"pradipvdeore@gmail.com", @"fromEmail",
                                               @"pavitrarupani89@gmail.com", @"toEmail",
                                               @"smtp.gmail.com", @"relayHost",
                                               @"mobileapp.qa@gmail.com", @"login",
                                               @"mobile@123", @"pass",
                                               [NSNumber numberWithBool:YES], @"requiresAuth",
                                               [NSNumber numberWithBool:YES], @"wantsSecure", nil];

    [userDefaults registerDefaults:defaultsDictionary];


    self.mapView.delegate=self;

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Custom Methods


-(IBAction)getMyLocation:(id)sender{
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;

    [locationManager startUpdatingLocation];
}


#pragma mark - CLLocationManagerDelegate

- (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];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"didUpdateToLocation: %@", newLocation);
    CLLocation *currentLocation = newLocation;

    if (currentLocation != nil) {
        lblLongitude.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
        lblLatitiude.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
    }

    // Stop Location Manager
    [locationManager stopUpdatingLocation];

    // Reverse Geocoding
    NSLog(@"Resolving the Address");
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        NSLog(@"Found placemarks: %@, error: %@", placemarks, error);
        if (error == nil && [placemarks count] > 0) {
            placemark = [placemarks lastObject];

            lblAdress.text = [NSString stringWithFormat:@"%@ %@\n%@ %@\n%@\n%@",
                                 placemark.subThoroughfare, placemark.thoroughfare,
                                 placemark.postalCode, placemark.locality,
                                 placemark.administrativeArea,
                                 placemark.country];



            MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(currentLocation.coordinate, 800, 800);
            [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];

            // Add an annotation
            MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
            point.coordinate = currentLocation.coordinate;
            point.title = @"Where am I?";
            point.subtitle = [NSString stringWithFormat:@"%@ %@\n%@ %@\n%@\n%@",
                              placemark.subThoroughfare, placemark.thoroughfare,
                              placemark.postalCode, placemark.locality,
                              placemark.administrativeArea,
                              placemark.country];


            [self.mapView addAnnotation:point];


        } else {
            NSLog(@"%@", error.debugDescription);
        }
    } ];


}

//My
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    MKAnnotationView *annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"loc"];
    annotationView.canShowCallout = YES;
    annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

    return annotationView;
}

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{

    [self getSignScreenShot];

    MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
    controller.mailComposeDelegate = self;
    [controller setSubject:@"My Subject"];
    [controller setMessageBody:@"Hello there." isHTML:NO];
    if (controller) [self presentModalViewController:controller animated:YES];
}

- (void)mailComposeController:(MFMailComposeViewController*)controller
          didFinishWithResult:(MFMailComposeResult)result
                        error:(NSError*)error;
{
    if (result == MFMailComposeResultSent) {
        NSLog(@"It's away!");
    }
    [self dismissModalViewControllerAnimated:YES];
}

//-----------------------------------------------------------------------------------
//This methos is to take screenshot of map
//-----------------------------------------------------------------------------------
-(UIImage *)getSignScreenShot
{
    CGRect rect = CGRectMake(self.mapView.frame.origin.x,self.mapView.frame.origin.y-50,self.mapView.frame.size.width+60,self.mapView.frame.size.height+15);
    UIGraphicsBeginImageContextWithOptions(self.mapView.frame.size, NO, 1.0);
    [self.mapView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
    CGImageRef imageRef = CGImageCreateWithImageInRect([screenshot CGImage], rect);
    UIImage *newImage = [UIImage imageWithCGImage:imageRef];

    return newImage;
}