2011-06-29 21 views
34

CoreLocationで私の現在地を見つける必要がありますが、私は複数の方法を試みましたが、これまでのところCLLocationManagerは0(.. 0.000.00.000)しか返していません。CoreLocationで現在地を見つける方法

ここで(を動作するように更新)私のコードです:

輸入

宣言
#import <CoreLocation/CoreLocation.h> 

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

機能

答えて

77

を見ますviewDidLoad中とNSStringとして現在位置をreturnできる機能作成:

- (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の初期化は、ユーザーが準備ができていないと良い考えではありません。そして、CLLocationManagerが初期化された後に、locationManager.location.coordinateは、latitudelongitudeを自由に得るために使用できます。

プロジェクト設定の[ビルドフェーズ]タブ(Targets->Build Phases->Link Binary)にCoreLocation.frameworkを追加することを忘れないでください。 // mobileorchard:ここ

+0

しかし、これらのメソッドはもはや現在の位置を返していません。私はXcode 6を使っていましたが、Xcode 5を使用するとうまくいきました。 – SARATH

15

CLLocationManagerを使用すると、すぐに位置情報を取得する必要はありません。位置情報を取得するGPSおよびその他のデバイスは、初期化されていない可能性があります。情報が得られるまでに時間がかかることがあります。代わりに、locationManager:didUpdateToLocation:fromLocation:に応答するデリゲートオブジェクトを作成し、それをロケーションマネージャの代理人として設定する必要があります。

インポートCoreLocation

#import <CoreLocation/CoreLocation.h> 

宣言CLLocationManager

CLLocationManager *locationManager; 

はを初期化

は、あなたがこのようなCoreLocationを使用して場所を見つけることができますhere

+2

この記事はhttpでの注釈の詳細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 

で現在位置を表示することができます。com/hello-there-a-corelocation-tutorial /(関連するstackoverflow質問から取得)は何をすべきかを示しています。 – ThomasW

-2

あなたは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:@"[email protected]", @"fromEmail", 
               @"[email protected]", @"toEmail", 
               @"smtp.gmail.com", @"relayHost", 
               @"[email protected]", @"login", 
               @"[email protected]", @"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; 
} 
関連する問題