这是我的代码,我正在尝试获取当前的经度和纬度,因此我的位置将显示在地图视图上。但是,位置管理器代表从未被调用,所以我总是得到经度 = 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
谁能给我一些建议。干杯