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

查看:20
本文介绍了如何使用 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:

import CoreLocation:

#import <CoreLocation/CoreLocation.h>

声明CLLocationManager:

CLLocationManager *locationManager;

初始化 viewDidLoad 中的 locationManager 并创建一个函数,该函数可以将当前位置作为 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.

不要忘记在 Build Phases 选项卡下的项目设置中添加 CoreLocation.framework(Targets->Build Phases->Link Binary).

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天全站免登陆