iphone - 如何在 objective-c 中获取纬度和经度的当前位置

标签 iphone objective-c core-location latitude-longitude

我正在使用以下代码获取当前位置,我已经添加了核心定位框架

- (void)viewDidLoad {
    [super viewDidLoad];

    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
    [locationManager startUpdatingLocation];

}

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    int degrees = newLocation.coordinate.latitude;
    double decimal = fabs(newLocation.coordinate.latitude - degrees);
    int minutes = decimal * 60;
    double seconds = decimal * 3600 - minutes * 60;
    NSString *lat = [NSString stringWithFormat:@"%d° %d' %1.4f\"", 
                     degrees, minutes, seconds];
    NSLog(@" Current Latitude : %@",lat);
    //latLabel.text = lat;
    degrees = newLocation.coordinate.longitude;
    decimal = fabs(newLocation.coordinate.longitude - degrees);
    minutes = decimal * 60;
    seconds = decimal * 3600 - minutes * 60;
    NSString *longt = [NSString stringWithFormat:@"%d° %d' %1.4f\"", 
                       degrees, minutes, seconds];
    NSLog(@" Current Longitude : %@",longt);
    //longLabel.text = longt;
}

但我得到的是默认值,即纬度:42° 17' 36.8898"和经度:-71° 27' 43.1003" 我当前的纬度:N 12° 56' 11.5624"和经度:E 77° 32' 41.0834"。如何获得准确的纬度和经度。 我哪里做错了,或者我需要添加任何其他方法或功能或框架。

提前致谢。

最佳答案

可以在需要获取当前经纬度的地方添加这个方法:

-(CLLocationCoordinate2D) getLocation{
    CLLocationManager *locationManager = [[[CLLocationManager alloc] init] autorelease];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    [locationManager startUpdatingLocation];
    CLLocation *location = [locationManager location];
    CLLocationCoordinate2D coordinate = [location coordinate];

    return coordinate;
}

并调用它:

CLLocationCoordinate2D coordinate = [self getLocation];
NSString *latitude = [NSString stringWithFormat:@"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:@"%f", coordinate.longitude];

NSLog(@"*dLatitude : %@", latitude);
NSLog(@"*dLongitude : %@",longitude);

关于iphone - 如何在 objective-c 中获取纬度和经度的当前位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8998558/

相关文章:

ios - CLVisit 是如何工作的?

iphone - 在核心数据中保存一对多关系时出现问题

iphone - 在iPhone邮件应用程序上绘制蓝色 "unread dot"

ios - 如何在没有混合图层的情况下获得具有渐变的图像?

objective-c - 在 obj-c (obj-c++) 模式下在 emacs 中的 header /实现之间切换缓冲区

ios - 终止的应用程序只会重新启动一次

iphone - 如何在iPhone上获取Wifi的RSSI?

iphone - 从 iPod 库获取播放列表 - Objective C

ios - 如何设置和传递也可以在另一个 View Objective-C 中访问的变量的值

ios - 无法从单独的变量/常量中的 CLLocationManager 获取坐标