【发布时间】:2013-06-22 16:39:32
【问题描述】:
这是我的代码,我正在尝试获取我当前的经度和纬度, 所以我的位置将显示在地图视图上。 但是,位置管理器代表永远不会被调用,所以我总是得到经度 = 0.0000 和纬度 = 0.0000.....
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
@interface MapViewController : UIViewController <CLLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property(retain,nonatomic)CLLocationManager *locationManager;
@property(assign,nonatomic)float longitude;
@property(assign,nonatomic)float latitude;
@end
这是实现文件:
#import "MapViewController.h"
#define METERS_PER_MILE 1609.344
@interface MapViewController ()
@end
@implementation MapViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc] init];
[self getCurrentLocation];
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = self.latitude;
zoomLocation.longitude = self.longitude;
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 0.5*METERS_PER_MILE, 0.5*METERS_PER_MILE);
[self.mapView setRegion:viewRegion animated:YES];
NSLog(@"longitu
de %f", self.longitude);
NSLog(@"latitude %f", self.latitude);
}
-(void)getCurrentLocation
{
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewDidUnload {
[self setMapView:nil];
[super viewDidUnload];
}
-(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 didUpdateLocations:(NSArray *)locations
{
NSLog(@"didUpdateToLocation: %@", [locations lastObject]);
CLLocation *currentLocation = [locations lastObject];
if (currentLocation != nil) {
self.longitude = currentLocation.coordinate.longitude;
self.latitude = currentLocation.coordinate.latitude;
NSLog(@"cal longitude %f", self.longitude);
NSLog(@"cal latitude %f", self.latitude);
}
}
@end
谁能给我一些建议。干杯
【问题讨论】:
-
委托方法的调用可能需要一些时间。我怀疑你会在调用 viewWillAppear 之前获得值。它从来没有被调用过吗?
-
如果委托方法
locationManager:didUpdateLocations根本没有被调用,那么请确保您在 iOS 6 上运行该应用,并且该应用被授权使用定位服务。
标签: ios delegates location mapkit cllocationmanager