如何使用CoreLocation查找当前位置 [英] How to find your current location with CoreLocation

查看:96
本文介绍了如何使用CoreLocation查找当前位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to find my current location with CoreLocation, I tried multiple methods but so far my CLLocationManager has only returned 0's.. (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];
}

推荐答案

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

You can find your location using CoreLocation like this:

导入CoreLocation:

#import <CoreLocation/CoreLocation.h>

声明CLLocationManager:

CLLocationManager *locationManager;

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

Initialize the locationManager in viewDidLoad and create a function that can return the current location as an 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函数将返回预期的位置:

And calling the deviceLocation function will return the location as expected:

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

这只是一个例子.在没有用户准备的情况下初始化CLLocationManager并不是一个好主意.而且,当然locationManager.location.coordinate可用于在初始化CLLocationManager之后随意获取latitudelongitude.

This is just an example. Initializing CLLocationManager without the user being ready for it isn't a good idea. And, of course, locationManager.location.coordinate can be used to get latitude and longitude at will after CLLocationManager has been initialized.

请不要忘记在项目设置的构建阶段"选项卡(Targets->Build Phases->Link Binary)下添加CoreLocation.framework.

Don't forget to add the CoreLocation.framework in your project settings under the Build Phases tab (Targets->Build Phases->Link Binary).

这篇关于如何使用CoreLocation查找当前位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆